生活随笔
收集整理的這篇文章主要介紹了
HihoCoder - 1457 后缀自动机四·重复旋律7(后缀自动机)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:點(diǎn)擊查看
題目大意:給出 n 個(gè)由 0~9 的數(shù)字組成的字符串,現(xiàn)在要求每個(gè)子串所表示的十進(jìn)制下數(shù)字的累加之和
題目分析:因?yàn)閷?duì)于字符串的所有子串而言數(shù)量無(wú)疑是非常龐大的,所以我們選擇用后綴自動(dòng)機(jī)+動(dòng)態(tài)規(guī)劃來(lái)解決,這次我們用不到后綴鏈接了,而是根據(jù)parent tree的性質(zhì),一直轉(zhuǎn)移答案,因?yàn)榧偃缒硞€(gè)節(jié)點(diǎn) cur?的下一個(gè)節(jié)點(diǎn) to 是當(dāng)前節(jié)點(diǎn)加上了數(shù)字 num 后形成的,那么轉(zhuǎn)移方程就是 val[ to ] += val[ cur ] * 10 + cnt[ cur ] * num,不過(guò)需要注意的是,雖然是單純的在parent tree上轉(zhuǎn)移,但還是要按照拓?fù)湫騺?lái)才行,以上說(shuō)的是對(duì)于一個(gè)字符串而言的,如果有多個(gè)字符串,我們可以用類(lèi)似于后綴數(shù)組的形式將其用特殊的符號(hào)拼接起來(lái),這里我們選擇用冒號(hào) ' : ' 拼接,因?yàn)槊疤?hào)的ASCII碼恰好是 ' 0 ' + 10 ,方便處理,在進(jìn)行轉(zhuǎn)移的時(shí)候,我們不選擇跨過(guò)冒號(hào)的點(diǎn)就好了
代碼:
?
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e6+100;const int mod=1e9+7;char s[N];int tot=1,last=1,id[N<<1],tong[N<<1],cnt[N<<1];LL val[N<<1];struct Node
{int ch[26];int fa,len;
}st[N<<1];void add(int x)
{int p=last,np=last=++tot;st[np].len=st[p].len+1;while(p&&!st[p].ch[x])st[p].ch[x]=np,p=st[p].fa;if(!p)st[np].fa=1;else{int q=st[p].ch[x];if(st[p].len+1==st[q].len)st[np].fa=q;else{int nq=++tot;st[nq]=st[q]; st[nq].len=st[p].len+1;st[q].fa=st[np].fa=nq;while(p&&st[p].ch[x]==q)st[p].ch[x]=nq,p=st[p].fa;//向上把所有q都替換成nq}}
}void radix_sort()
{for(int i=1;i<=tot;i++)tong[st[i].len]++;for(int i=1;i<=tot;i++)tong[i]+=tong[i-1];for(int i=1;i<=tot;i++)id[tong[st[i].len]--]=i;
}int main()
{
//#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
//#endif
// ios::sync_with_stdio(false);int n;scanf("%d",&n);while(n--){scanf("%s",s);int len=strlen(s);for(int i=0;i<len;i++)add(s[i]-'0');if(n)add(10);}radix_sort();cnt[1]=1;for(int i=1;i<=tot;i++){int cur=id[i];for(int j=0;j<10;j++){int to=st[cur].ch[j];if(to){cnt[to]+=cnt[cur];val[to]=(val[to]+(val[cur]*10+1LL*cnt[cur]*j)%mod)%mod;}}}LL ans=0;for(int i=1;i<=tot;i++)ans=(ans+val[i])%mod;printf("%lld\n",ans);return 0;
}
?
超強(qiáng)干貨來(lái)襲 云風(fēng)專(zhuān)訪(fǎng):近40年碼齡,通宵達(dá)旦的技術(shù)人生
總結(jié)
以上是生活随笔為你收集整理的HihoCoder - 1457 后缀自动机四·重复旋律7(后缀自动机)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。