CodeForces - 432D Prefixes and Suffixes(KMP的next数组性质)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                CodeForces - 432D Prefixes and Suffixes(KMP的next数组性质)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                題目鏈接:點擊查看
題目大意:給出一個字符串,求滿足條件的所有子字符串在主串中出現的次數,條件就是當前子字符串在主串中既是前綴也是后綴
題目分析:因為今天小冰給我講了一個與next數組配合的dp,也就是dp[i]代表的就是截止到i為止的前綴在主串中出現的次數,和這個題簡直是般配,直接先對主串跑一遍next,再對next跑一遍dp,然后利用next[n]不斷回溯即可,因為回溯時得到的答案都是反著的,所以我們可以用一個棧來儲存答案,最后直接輸出即可,注意對于子串就是主串的情況需要特判,因為next數組求出的只能是前綴和后綴(不包含主串的子串)
代碼:
#include<iostream> #include<cstdlib> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<climits> #include<cmath> #include<cctype> #include<stack> #include<queue> #include<list> #include<vector> #include<set> #include<map> #include<sstream> #include<unordered_map> using namespace std;typedef unsigned long long ull;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e5+100;const int mod=1e9+7;int n;char s[N];int nx[N];int dp[N];void getnext()//跑next數組 {nx[0]=-1;int i=0,j=-1;while(i<n){if(j==-1||s[i]==s[j])nx[++i]=++j;elsej=nx[j];} }pair<int,int> mp(int a,int b)//偷懶的函數。。 {return make_pair(a,b); }int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);scanf("%s",s);n=strlen(s);getnext();for(int i=1;i<=n;i++)//初始化dp[i]=1;for(int i=n;i>=1;i--)//跑dp數組dp[nx[i]]+=dp[i];stack<pair<int,int>>ans;ans.push(mp(n,1));int pos=nx[n];while(pos){ans.push(mp(pos,dp[pos]));pos=nx[pos];}printf("%d\n",ans.size());while(!ans.empty()){printf("%d %d\n",ans.top().first,ans.top().second);ans.pop();}return 0; }?
總結
以上是生活随笔為你收集整理的CodeForces - 432D Prefixes and Suffixes(KMP的next数组性质)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: CodeForces - 222C Re
- 下一篇: CodeForces - 1236D A
