字符串(多串后缀自动机):HDU 4436 str2int

str2int

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 2082    Accepted Submission(s): 744

Problem Description
In this problem, you are given several strings that contain only digits from '0' to '9', inclusive.
An example is shown below.
101
123
The set S of strings is consists of the N strings given in the input file, and all the possible substrings of each one of them.
It's boring to manipulate strings, so you decide to convert strings in S into integers.
You
can convert a string that contains only digits into a decimal integer,
for example, you can convert "101" into 101, "01" into 1, et al.
If an integer occurs multiple times, you only keep one of them.
For example, in the example shown above, all the integers are 1, 10, 101, 2, 3, 12, 23, 123.
Your task is to calculate the remainder of the sum of all the integers you get divided by 2012.
 
Input
There are no more than 20 test cases.
The test case starts by a line contains an positive integer N.
Next N lines each contains a string consists of one or more digits.
It's guaranteed that 1≤N≤10000 and the sum of the length of all the strings ≤100000.
The input is terminated by EOF.
 
Output
An integer between 0 and 2011, inclusive, for each test case.
 
Sample Input
5
101
123
09
000
1234567890
 
Sample Output
202
 
  这道题用后缀自动机可以很好地解决,这里应用的性质是SAM的每一条转移代表的字串都不相同,而且包含所有子串,TOT表示当前有多少个相同前缀,在后面拼接一个数,只需要将原SUM*10再加上当前贡献TOT*j即可。
 #include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int mod=;
const int maxn=;
int cnt,last,n,ans,sum[maxn];
int wv[maxn],sa[maxn],tot[maxn];
int ch[maxn][],fa[maxn],len[maxn];
struct SAM{
void Init(){
memset(ch,,sizeof(ch));
memset(fa,,sizeof(fa));
memset(len,,sizeof(len));
last=cnt=;
}
void Insert(int c){
int p=last,np=last=++cnt;len[np]=len[p]+;
while(p&&!ch[p][c])ch[p][c]=np,p=fa[p];
if(!p)fa[np]=;
else{
int q=ch[p][c];
if(len[p]+==len[q])
fa[np]=q;
else{
int nq=++cnt;len[nq]=len[p]+;
memcpy(ch[nq],ch[q],sizeof(ch[q]));
fa[nq]=fa[q];fa[q]=fa[np]=nq;
while(p&&ch[p][c]==q)
ch[p][c]=nq,p=fa[p];
}
}
} void Extend(char *s){
int l=strlen(s);last=;
for(int i=,c;i<l;i++){
c=s[i]-'';
if(!ch[last][c]||len[ch[last][c]]!=i+)
Insert(c);
else
last=ch[last][c];
}
}
}sam; char s[maxn]; int main(){
while(scanf("%d",&n)!=EOF){
sam.Init();
for(int i=;i<=n;i++)
scanf("%s",s),sam.Extend(s); memset(wv,,sizeof(wv));
memset(sa,,sizeof(sa));
for(int i=;i<=cnt;i++)
wv[len[i]]++;
for(int i=;i<=cnt;i++)
wv[i]+=wv[i-];
for(int i=cnt;i>=;i--)
sa[--wv[len[i]]]=i;
memset(tot,,sizeof(tot));
memset(sum,,sizeof(sum));
tot[]=;ans=;
for(int i=;i<cnt;i++){
int x=sa[i];
for(int j=;j<=;j++){
if(x==&&j==)continue;
(tot[ch[x][j]]+=tot[x])%=mod;
(sum[ch[x][j]]+=(sum[x]*+tot[x]*j))%=mod;
}
(ans+=sum[x])%=mod;
}
printf("%d\n",ans);
}
}

  

 
上一篇:使用存储即服务优化混合云平台


下一篇:Mysql联合查询UNION和UNION ALL的使用介绍