142. Keyword time limit per test: 0.5 sec. 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 contiguous substring (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 11 aabaaabbbab Sample Output 4 aaaa | ||||||
|
首先我们知道长度为L的串有2^L种可能,而在母串N中长度为L的子串有N-L+1种可能,假定这N-L+1种可能互不相同(有相同的话情况更少),则若该长度下有解,那么必有2^L>N-L+1,即L>log2(N),N=500000,所以L>=log2(500000)时即L>=19时,必定有解,因此可得,最短的串长必定<=19,因此我们做一个哈希,把长度为L的N的子串存入哈希中(1<=L<=19),时间复杂度为O(N),常数为19,问题就得到解决了。
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 500005;
int N = 0;
char str[MAXN] = {0};
bool f[20][(1<<19)+2] = {0};
void print(int l, int num)
{
char x[20] = {0};
int t = l-1;
while(num)
{
x[t--] = num&1;
num >>= 1;
}
for(int i = 0; i < l; ++i)
printf("%c", x[i]+'a');
}
int main()
{
scanf("%d\n", &N);
scanf("%s", str);
for(int i = 0, lim = strlen(str); i < lim; ++i)
{
int now = 0;
for(int j = 0; i-j >= 0 && j < 19; ++j)
{
now += (str[i-j]-'a')*(1<<j);
f[j][now] = true;
}
}
for(int i = 0; i < 19; ++i)
for(int j = 0, lim = 1<<(i+1); j < lim; ++j)
if(f[i][j] == false)
{
printf("%d\n", i+1);
print(i+1, j);
return 0;
}
return 0;
}