C. Palindromifier(思维+构造)Codeforces Round #676 (Div. 2)

原题链接: https://codeforces.com/contest/1421/problem/C

在这里插入图片描述
测试样例

input
abac
output
2
R 2
R 5
input
acccc
output
2
L 4
L 2
input
hannah
output
0

Note

For the first example the following operations are performed:
abac → abacab → abacaba

The second sample performs the following operations: acccc → cccacccc → ccccacccc
The third example is already a palindrome so no operations are required.

题意: 给你一个长度为 n n n的字符串 s s s,你可以进行两种操作:

  • 第一种操作允许你选择 i ( 2 ≤ i ≤ n − 1 ) i (2≤i≤n−1) i(2in1) 然后将子串 s 2 s 3 … s i ( i − 1 s_2s_3…s_i (i−1 s2s3si(i1长度的字符串 ) ) )反转追加到字符串 s s s的前面。
  • 第二种操作允许你选择 i ( 2 ≤ i ≤ n − 1 ) i (2≤i≤n−1) i(2in1) 然后将子串 s i s i + 1 … s n − 1 ( i − 1 s_is_{i+1}…s_{n-1} (i−1 sisi+1sn1(i1长度的字符串 ) ) )反转追加到字符串 s s s的前面。

其中 n n n为字符串实时长度,你需要构造一个字符串,使得成为一个回文串。

解题思路: 这种题目存在着很多情况,而这些情况是根本列不完的,所以我们处理这类问题中一定要想出一个通解,即我们进行的操作能使输入的字符串都变成回文串。OK,那么我们可以自己建一个特殊的样例,不必太复杂,例如 a b c d abcd abcd,这个就是最极端的情况,即所有字符都不相同,那么我们来看。

对于 a b c d abcd abcd,我们如果进行第二步操作将 b c d bcd bcd反转放到最前面去,那么我们发现这就是一个回文串。然而,我们并不能这么做,因为我们进行第二种操作只能从第二个字符到第 n − 1 n-1 n1个字符,所以我们需要添加一个字符到后面去,那么添加了之后我们是不是得添加一个相同的字符到前面去,这时候我们想想,经过上述处理的字符串是不是一个回文字符串,那么该如何进行操作呢?首先我们如果要获取一个字符,放到前面去则必须选择第二个字符,放到后面去必须选择第 n − 1 n-1 n1个字符。
那么我们先将第 3 3 3个字符放到后面去,则进行 R    3 R\space \space 3 R  3,字符串变为如下:
abcdc
ok,那么我们需要让 b c d bcd bcd反转到前面去,则进行 L    4 L\space \space 4 L  4。那么字符串变为如下:
dcbabcdc
这个时候就是我们想要的了,现在我们需要将最后一个字符放到最前面去,这该怎么办呢?别急,因为要将一个字符放到前面去,我们只能选择第二个字符,而第二个字符是不是由反转得到的,而这个反转的字符是不是那个第 n − 1 n-1 n1个字符,而那个第 n − 1 n-1 n1个字符是不是最后一个字符,仔细看第一步操作,故我们进行 L    2 L\space \space 2 L  2,即可让字符串变为回文串。

AC代码

/*
*邮箱:[email protected]
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h>	//POJ不支持

#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair

using namespace std;

const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll>  pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//

//样例测试
//abcd
//abcdc/构造出一个相等的字符。
//构造以前面为回文的字符串。
//dcbabcdc
//取我们构造出相等的字符。即2处。
//cdcbabcdc
string s;
int main(){
    
    
	//freopen("in.txt", "r", stdin);//提交的时候要注释掉
	IOS;
	while(cin>>s){
    
    
		cout<<3<<endl;
		int n=s.size();
		cout<<"R "<<n-1<<endl;
		cout<<"L "<<n<<endl;
		cout<<"L "<<2<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hzf0701/article/details/109162319
今日推荐