142. Keyword
time limit per test: 1 sec.
memory limit per test: 16384 KB
Kevin has inventeda new algorithm to crypt and decrypt messages, which he thinks is unbeatable.The algorithm uses a very large key-string, out of which a keyword is foundout after applying the algorithm. Then, based on this keyword, the messageis easily crypted or decrypted. So, if one would try to decrypt some messagescrypted with this algorithm, then knowing the keyword would be enough.Someone has found out how the keyword is computed from the large key-string,but because he is not a very experienced computer programmer, he needsyour help. The key-string consists of N characters from the set{'a','b'}.The keyword is the shortest non-empty string made up of the letters 'a'and 'b', which is not contained as a contiguous substring(also called subsequence) inside the key-string. It is possible that morethan one such string exists, but the algorithm is designed in such a waythat any of these strings can be used as a keyword. Given the key-string,your task is to find one keyword.
Input
The first line containsthe integer number N, the number of characters inside the key-string(1<= N <= 500 000). The next line contains N charactersfrom the set {'a','b'} representing the string.
Output
The first line ofoutput should contain the number of characters of the keyword. The secondline should contain the keyword.
Sample Input
11
aabaaabbbab
Sample Output
4
aaaa
暴力枚举长度,然后yy
贴上代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<vector>
#include<cstdlib>
#define inf 0xfffffff
#define CLR(a,b) memset((a),(b),sizeof((a)))
#define FOR(a,b) for(int a=1;a<=(b);(a)++)
using namespace std;
int const nMax = 501010;
int const base = 10;
typedef int LL;
typedef pair<LL,LL> pij;
// std::ios::sync_with_stdio(false);
char s[nMax];
int a[nMax];
bool b[(1<<20)];
int c[nMax];
int ans,len,n;
bool ok;
void output(int ans,int len) {
if(len==0) return ;
output(ans/2,len-1);
if(ans&1) printf("a");
else printf("b");
return ;
}
void find() {
int cp=1;
while(1) {
for(int i=0;i<(1<<(cp+1)) ;i++) b[i]=false;
for(int i=n-1 ;i >=cp; i-- ){
c[i]=c[i-1]*2+a[i]; //printf("%d \n ",c[i]);
b[c[i]]=true;
}
for(int i=0 ; i<(1<<(cp+1)) ;i++) if(!b[i]) {
printf("%d\n",cp+1);
output(i,cp+1);
return ;
}
cp++;
}
return ;
}
int main(){
scanf("%d%s",&n,s) ;
ok=false;
for(n=0;s[n];n++){
a[n]=(s[n]=='a')?(1):(0);
c[n]=a[n];
b[a[n]]=true;
}
if(!b[0]) {
printf("1\nb\n");
return 0;
}else if(!b[1]){
return printf("1\na\n"),0;
}
find();
return 0;
}