CodeForces-1109B. Sasha and One More Name

本文解析了Codeforces比赛中的D题,题目要求找到将给定的回文串通过最少次数的剪切和重新拼接形成新回文串的方法。文章详细分析了三种可能的输出情况,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:https://codeforces.com/contest/1109/problem/D

题意:

给出一段回文串,问最少对其剪切几次后进行重新拼接可以形成新的回文串

分析:输出无非三种情况:impossible 1, 2;

字符串长度为n;

impossible : n个或者n - 1个字符相同。

1:循环字符串,这个只要找出循环节进行循环,如果可以得到和原串不同的就是答案;

2: 从头找到一个长度小于 n / 2 的子串,从后边也找到相应的串,前后对换,判断得到的串是否符合要求;

#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>

using namespace std;

const int maxn = 100005;
char s[maxn];

int main()
{
    cin >> s;
    int cnt = 0;
    char s1[maxn];
    int n = strlen(s);
    for(int i = 1;i < n;i ++)
    {
        if(s[i] != s[0]) cnt = 1;
    }
    if(cnt == 0)
    {
        cout << "Impossible" << endl;
    }
    else
    {
        for(int p = 1;p < n;p ++)
        {
            int t = 0;
            int x = 0,flag = 0;
            for(int k = p;k < n;k ++)
            {
                s1[t ++] = s[k];
            }
            for(int k = 0;k < p;k ++)
            {
                s1[t ++] = s[k];
            }
            for(int i = 0;i < n;i ++)
            {
                if(s1[i] != s[i])
                {
                    flag = 1;
                }
            }
            if(flag == 0)continue;
            int l = 0,r = n - 1;
            while(l <= r)
            {
                if(s1[l] != s1[r])
                {
                    x = 1;
                }
                l ++;
                r --;
            }
            if(x == 0) {
                cout << "1" << endl;
                return 0;
            }
        }
        if(n % 2)
        {
            int a = 0;
            int k = n / 2;
            for(int i = k - 1;i >= 1;i --)
            {
                if(s[i] != s[0]) a = 1;
            }
            if(a == 0) cout << "Impossible" << endl;
            else cout << "2" << endl;
        }
        else cout << "2" << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值