XVIII Open Cup named after E.V. Pankratiev Stage 6, Grand Prix of Ukraine Problem F. Bad Word

Marichka has seen bad word while surfing the net! She immediately starts crying and asks Zenyk to
destroy it.
Zenyk knows that Marichka saw word S which consists of lower case english characters. Zenyk can
delete any substring SlSl+1Sl+2 … Sr of this word in one minute. But he knows that Marichka is keen
on palindromes so if this substring is palindrome, Marichka will resent. Zenyk decided that he wouldn’t
delete such substrings. Now Zenyk wants to know minimum time to destroy bad word or if it is impossible.
Palindrome is such string that reads the same backward as forward. For example, strings “bob”, “abba”,
“aaaa” are palindromes and “cat”, “dog”, “penguin” are not.
Input
First line contains one integer N – length of the word S (1 ≤ N ≤ 105
). Second line contains word S
which consists of lower case english characters.
Output
Print minimum number of minutes to destroy bad word or −1 if it is impossible.
Examples
standard input standard output
7
abcdcba
2
3
xxx
-1
Note
In the first case Zenyk can delete substring “bcd” during the first minute. Remaining word equals “acba”
and can be deleted during the second minute.

题意:给定一个字符串,每次可以删去一个不是回文串的字串,问可不可以最终将其全部删去,如果可以,输出最小次数,否则输出-1;

思路:如果不是回文串,自然1次即可;对于 aaaaaa,aaabaaa,ababababa….这种,肯定是-1;其他情况就是2;
( 感谢 Claris 老师)

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<string>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
using namespace std;
#define maxn 200005
#define inf 0x3f3f3f3f
#define INF 0x7fffffff
typedef long long  ll;
typedef unsigned long long ull;
#define ms(x) memset(x,0,sizeof(x))
const long long int mod = 1e9 + 7;
#define eps 1e-7
typedef pair<int,int>pii;

inline int read()
{
    int x = 0, k = 1; char c = getchar();
    while (c < '0' || c > '9') { if (c == '-')k = -1; c = getchar(); }
    while (c >= '0' && c <= '9')x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
    return x * k;
}

int quickpow(int a,int b)
{
    int ans=1;
    while(b){
        if(b&1)ans=ans*a;
        b>>=1;
        a=a*a;
    }
    return ans;
}

int n;
char a[maxn];

int main()
{
    //ios::sync_with_stdio(false);
    n=read();
    int i;
    scanf("%s",a+1);
    for( i=1;i<=n;i++)if(a[i]!=a[n-i+1])break;
    if(i<=n){
        cout<<1<<endl;return 0;
    }
    for(i=1;i<=n;i++)if(a[i]!=a[1])break;
    if(i>n){
        cout<<-1<<endl;return 0;
    }
    if(n%2==0){
        cout<<2<<endl;return 0;
    }
    for(i=1;i<=n/2;i++){
        if(a[i]!=a[1])break;
    }
    if(i>n/2){cout<<-1<<endl;return 0;}
    for(i=1;i<=n;i++){
        if(i>2&&a[i]!=a[i-2])break;
    }
    if(i>n){cout<<-1<<endl;return 0;};
    cout<<2<<endl;
}






猜你喜欢

转载自blog.csdn.net/qq_40273481/article/details/81812664