标签:
Dr. Ellie Arroway has established contact with an extraterrestrial civilization. However, all efforts to decode their messages have failed so far because, as luck would have it, they have stumbled upon a race of stuttering aliens! Her team has found out that, in every long enough message, the most important words appear repeated a certain number of times as a sequence of consecutive characters, even in the middle of other words. Furthermore, sometimes they use contractions in an obscure manner. For example, if they need to saybab twice, they might just send the message babab, which has been abbreviated because the second b of the first word can be reused as the first b of the second one.
Thus, the message contains possibly overlapping repetitions of the same words over and over again. As a result, Ellie turns to you, S.R. Hadden, for help in identifying the gist of the message.
Given an integer m, and a string s, representing the message, your task is to find the longest substring of sthat appears at least m times. For example, in the message baaaababababbababbab, the length-5 word babab is contained 3 times, namely at positions 5, 7 and 12 (where indices start at zero). No substring appearing 3 or more times is longer (see the first example from the sample input). On the other hand, no substring appears11 times or more (see example 2).
In case there are several solutions, the substring with the rightmost occurrence is preferred (see example3).
3 baaaababababbababbab 11 baaaababababbababbab 3 cccccc 0
5 12 none 4 2
/** UvaLA 4513 hash (白书P225) 题目大意: 有一个口吃的外星人,说话的时候包含很多重复的字符串,给出外星人说的一句话,找出至少出现m次的最长字符串,如果存在输出长度和该字符串起始位置的最大值 解题思路: 二分答案L,然后判断是否有长度为L的字符串出现了至少m次。判断的方法很简单,从左到右计算出所有起始位置的长度为L的字符串的哈希值,一旦哈希值出现了至少m次 就有解。 值得一提的是二分的时候注意处理循环的满足条件。 */ #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; typedef unsigned long long LL; const int maxn=40000+10; const int hashseed=31; int n,m,pos; LL Hash[maxn];///Hash[i]表示长度为L以i为起点的字符串的哈希值 LL seed[maxn],has[maxn];///前者为种子的幂,后者为以i为起点的后缀的哈希值 int R[maxn]; int cmp(const int& a,const int& b) { return Hash[a]<Hash[b] || (Hash[a]==Hash[b] && a<b); } int ok(int L) { int c=0; pos=-1; for(int i=0;i<n-L+1;i++) { R[i]=i; Hash[i]=has[i]-has[i+L]*seed[L]; } sort(R,R+n-L+1,cmp);///按照哈希值排序,哈希值若相同序号小的优先 for(int i=0;i<n-L+1;i++) { if(i==0||Hash[R[i]]!=Hash[R[i-1]])c=0; if(++c>=m)pos=max(pos,R[i]); } return pos>=0; } int main() { char s[maxn]; while(~scanf("%d%*c",&m)) { if(m==0)break; scanf("%s",s); n=strlen(s); has[n]=0; for(int i=n-1;i>=0;i--) has[i]=has[i+1]*hashseed+(s[i]-'a'); seed[0]=1; for(int i=1;i<=n;i++) seed[i]=seed[i-1]*hashseed; if(!ok(1)) { printf("none\n"); } else { ///二分略带技巧性,我们要枚举的长度是(1~n), 并且最终的结果是求满足条件的最大值,因此r要定到n+1,循环条件要r-l>1 int l=1,r=n+1; while(r-l>1) { int mid=l+(r-l)/2; if(ok(mid)) l=mid; else r=mid; } ok(l); printf("%d %d\n",l,pos); } } return 0; }
标签:
原文地址:http://blog.csdn.net/lvshubao1314/article/details/42191607