SGU 142. Keyword(暴力枚举)

来源:互联网 发布:手机淘宝6.3.2 旧版本 编辑:程序博客网 时间:2024/06/09 11:22

Kevin has invented a 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 found out after applying the algorithm. Then, based on this keyword, the message is easily crypted or decrypted. So, if one would try to decrypt some messages crypted 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 needs your 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 contiguoussubstring (also called subsequence) inside the key-string. It is possible that more than one such string exists, but the algorithm is designed in such a way  that 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 contains the integer number N, the number of characters inside the key-string (1 <= N <= 500 000). The next line contains N characters from the set {'a','b'} representing the string.

Output

The first line of output should contain the number of characters of the keyword. The second line should contain the keyword.

Sample Input

11aabaaabbbab

Sample Output

4aaaa

题意:给你一个长度为n的只有'a' , 'b'字符组成的字符串,让你找出最短的不是这个字符串的子串的字符串。

思路:对于一个字符串,他最多有n-L+1个长度为L的子串,因为这题里的字符串只有两种字符,所以长度为L的字符串最多有2^L种。所以要求出最小的L,就要满足n-L+1 < 2^L ,所以L最长为19,直接枚举就可以了。


#include<vector>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#define LL long longusing namespace std;char s[500010];int a[30];bool f[(1<<19)+10][20];int main(void){    int n,i,j;    scanf("%d",&n);    scanf("%s",s);    memset(f,0,sizeof(f));    for(i=0;i<n;i++)    {        int t = 0;        for(j=0;j<19;j++)        {            if(i + j >= n)                break;            t = t*2 + s[i+j]-'a';            f[t][j+1] = 1;        }    }    int flag = 0;    for(j=1;j<=19;j++)    {        for(i=0;i<(1<<j);i++)        {            if(f[i][j] == 0)            {                flag = 1;                break;            }        }        if(flag == 1)            break;    }    printf("%d\n",j);    int c = j;    memset(a,0,sizeof(a));    while(i)    {        a[c--] = i%2;        i/=2;    }    for(i=1;i<=j;i++)        if(a[i] == 0)            printf("a");        else            printf("b");    return 0;}