Problem Codeforces Round #539 (Div. 2) - D. Sasha and One More Name
Time Limit: 1000 mSec
Problem Description
Input
The first line contains one string s (1≤|s|≤5000) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that s is a palindrome.
Output
Print one integer k — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
Sample Input
nolon
Sample Output
2
题解:这个题有个很良心的样例,就是"qqqq"的结果是无解,看到这个样例的第一反应就是如果有两个不同的字符就肯定可以(这里有点小问题),并且至多两次就可以构造出新的回文串,其实如果熟悉这种题目的话到这里就结束了,接下的工作就是验证能不能只剪一次,根据s的长度可知O(n^2)的复杂度是完全可以接受的,枚举在哪剪开,再进行判断即可,刚才有点问题的说法的反例就是 aba,这种就是无解的情况,其实稍加改进即可,也就是判断前 [n/2]个字符是否只有一种字符,如果不是那么原始串必定形如
a...b...b...a
这样就不会无解,反之如果只有一种字符,对于长度为偶数的串,相当于整个串只有一种字符,对于长度为奇数的串,相当于aba的情况,都是无解的,判断完无解之后就只剩枚举判断是否能够只剪一次了。
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 #define REP(i, n) for (int i = 1; i <= (n); i++) 6 #define sqr(x) ((x) * (x)) 7 8 const int maxn = 100000 + 100; 9 const int maxm = 200000 + 100; 10 const int maxs = 10000 + 10; 11 12 typedef long long LL; 13 typedef pair<int, int> pii; 14 typedef pair<double, double> pdd; 15 16 const LL unit = 1LL; 17 const int INF = 0x3f3f3f3f; 18 const double eps = 1e-14; 19 const double inf = 1e15; 20 const double pi = acos(-1.0); 21 const int SIZE = 100 + 5; 22 const LL MOD = 1000000007; 23 24 string str; 25 26 bool is_pd(string &s) 27 { 28 int len = s.size(); 29 for (int i = 0, j = len - 1; i < j; i++, j--) 30 { 31 if (s[i] != s[j]) 32 return false; 33 } 34 return true; 35 } 36 37 int main() 38 { 39 ios::sync_with_stdio(false); 40 cin.tie(0); 41 //freopen("input.txt", "r", stdin); 42 //freopen("output.txt", "w", stdout); 43 cin >> str; 44 int len = str.size(); 45 bool ok = false; 46 for (int i = 1; i < len / 2; i++) 47 { 48 if (str[i] != str[i - 1]) 49 { 50 ok = true; 51 break; 52 } 53 } 54 if (!ok) 55 { 56 cout << "Impossible" << endl; 57 return 0; 58 } 59 int ans = 2; 60 string tmp = ""; 61 for (int i = 1; i < len; i++) 62 { 63 tmp += str[i - 1]; 64 string tt = str.substr(i, len) + tmp; 65 if (tt != str && is_pd(tt)) 66 { 67 ans = 1; 68 break; 69 } 70 } 71 cout << ans << endl; 72 return 0; 73 }