sgu142:Keyword

142. Keyword

time limit per test: 0.5 sec. 
memory limit per test: 16384 KB

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

Author: Mugurel Ionut Andreica
Resource: SSU::Online Contester Fall Contest #2
Date: Fall 2002
题意大致为有个长度为N的串,由a或b构成,然后求出一个不是该串子串的最短的串的长度与该长度下的一种解。

首先我们知道长度为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;	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值