Codeforces #676 (Div. 2) C. Palindromifier (思维)

Codeforces #676 (Div. 2) C. Palindromifier (思维)

题目链接:https://codeforces.ml/contest/1421/problem/C

在这里插入图片描述
题意:
给定一个字符串,可以通过L或者R操作,将该字符串变成一个回文字符串。乍一看,好复杂,再细看这句话。

It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.

翻译过来就是:在这些约束下,总有一个解决方案。还请注意,您不必最小化应用的操作数量和结果字符串的长度,但是它们必须符合约束条件。

(总而言之就是,有多种情况的话,只需写出一种情况即可!)

有一个 万能 的方式:
例子:
abac
1.先存字符串的长度len = str.size()

2.先将倒数第二个字符即a拉到字符串后面,就是R len - 1;
3.再将2到n-1个字符,即ba,先翻转成ab,再放到字符串开头 L len;
4.此时第二个字符就是最后一个字符 len - 1,即 L 2;

在这里插入图片描述
Perfect !!!

上代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<algorithm>

#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define ll long long
//#define int ll
#define INF 0x3f3f3f3f
using namespace std;
int read()
{
    
    
	int w = 1, s = 0;
	char ch = getchar();
	while (ch < '0' || ch>'9') {
    
     if (ch == '-') w = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') {
    
     s = s * 10 + ch - '0';    ch = getchar(); }
	return s * w;
//最大公约数
}int gcd(int x,int y) {
    
    
    if(x<y) swap(x,y);//很多人会遗忘,大数在前小数在后
    //递归终止条件千万不要漏了,辗转相除法
    return x % y ? gcd(y, x % y) : y;
}
int lcm(int x,int y)//计算x和y的最小公倍数
{
    
    
    return x * y / gcd(x, y);//使用公式
}
//------------------------ 以上是我常用模板与刷题几乎无关 ------------------------//
int main()
{
    
    
	string str;
	cin >> str;
	int len = str.size();
	printf("3\n");
	printf("R %d\n", len - 1);
	printf("L %d\n", len);
	printf("L 2\n");
	return 0;
}

Java代码:


import java.util.Scanner;
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        System.out.println("3");
        int n = str.length();
        System.out.println("R " + (n - 1));
        System.out.println("L " + n);
        System.out.println("L 2");
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46272108/article/details/109249956