码迷,mamicode.com
首页 > 其他好文 > 详细

CodeForces 486C Palindrome Transformation

时间:2015-08-03 20:39:34      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

  题目:戳我

  题意:给定长度为n的字符串,给定初始光标位置p,支持4种操作,left,right移动光标指向,up,down,改变当前光标指向的字符,输出最少的操作使得字符串为回文。

  分析:只关注字符串n/2长度,up,down操作是固定不变的,也就是不能优化了,剩下就是left,down的操作数,细想下中间不用管,只关注从左到中间第一个要改变的位置和最后一个要改变的位置即可,具体看代码。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring> 
 4 #include <algorithm> 
 5 using namespace std;
 6 const int M = 1e5+5;
 7 
 8 int n, p;
 9 char str[M];
10 int main()
11 {
12     while( ~scanf("%d %d", &n, &p ) )  {
13         getchar();
14         gets( str+1 );
15         int sumchg = 0;  //up,down的操作总数
16         int first = 0;  //第一个要改变的位置
17         bool firstjd = true;
18         int last = 0;  //最后一个要改变的位置
19         for( int i=1; i<=n/2; i++ )  {
20             int d = abs( str[i]-str[n+1-i] );
21             if( d ) {
22                 if( firstjd )   {
23                     first = i;
24                     firstjd = false;
25                 }
26                 last = i;
27                 sumchg += min( d, 26-d );  //选择up或者down的最小操作数
28             }
29         }
30         if( p > n/2 )  //由于回文左右对称,所以p在中间右边时也可将p当左边对称位置计算
31             p = n+1-p;
32         int ret = 0;
33         if( sumchg == 0 )   {  //不需要改变输出0
34             printf("%d\n", ret);
35             continue;
36         }
37         if( first >= p )  //如果p在第一个要改变的左边,p只能向右走,即执行right操作
38             ret += sumchg + last - p; 
39         else if( last <= p )  //如果p在最后一个要改变的右边,p只能向左走,即执行left操作
40             ret += sumchg + p - first;
41         else
42             ret += min( 2*(p-first)+last-p, 2*(last-p)+p-first ) + sumchg;  //p在中间,取求向左向右走的最小值
43         printf("%d\n", ret);
44     }
45     return 0;
46 }

 

 

CodeForces 486C Palindrome Transformation

标签:

原文地址:http://www.cnblogs.com/TaoTaoCome/p/4700216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!