HDU5129 - Yong Zheng's Death
生活随笔
收集整理的這篇文章主要介紹了
HDU5129 - Yong Zheng's Death
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
HDU5129 - Yong Zheng's Death
做法:看題之后,就想到要建好trie樹,然后輸出非根節點數的平方,這樣顯然錯了。因為會出現重算的情況,即:你有 ab,cde ,abc,de, abcd, e,這幾個串那么 [ab, cde] [abc,de] [abcd,e] 都可以組成 abcde,那么就算了3次,答案就要減2。我們可以發現對于一個拼接好的串,他可能是由若干個對串構成的,這些串的分界線,將整個串分成了幾份,我們要減去的就是多的份數,那么就考慮對于一個串存在多少份這樣的串。對于一個節點S,他的fail指針指向的就是他的后綴對應的最長公共前綴,而S去除fail[S]的串,如果是其他前綴串的后綴,那么這個串會被重算。所以先在的問題就是對于每個串求出,以他為后綴的前綴的串的數目。而fail樹對應節點的子樹大小就是以這個串為后綴的前綴串的數目。參考了這篇BLOG
#include <bits/stdc++.h> #define pb push_back typedef long long ll; const int N = 3e6+7; using namespace std; int n, T[N][26], cc, fail[N], fa[N], sum[N]; char str[66]; vector< int > G[N]; void init() {for(int i = 0; i <= cc; ++i) {memset(T[i],0,sizeof(T[i]));fail[i] = fa[i] = 0;G[i].clear();}cc = 0; } void ins(char str[]) {int len = strlen(str), now = 0;for(int i = 0; i < len ; ++i) {int t = str[i] - 'a';if(!T[now][t]) T[now][t] = ++cc, fa[cc] = now;now = T[now][t];} } void build_ac() {queue< int > q; while(!q.empty()) q.pop();for(int i = 0; i < 26; ++i) if(T[0][i]) q.push(T[0][i]);while( !q.empty() ) {int u = q.front(); q.pop();for(int i = 0; i < 26; ++i) {if(T[u][i]) fail[T[u][i]] = T[fail[u]][i], q.push(T[u][i]);else T[u][i] = T[fail[u]][i];}} } void dfs(int u) {sum[u] = 1;for(int i = 0; i < G[u].size(); ++i) {int v = G[u][i];dfs(v); sum[u] += sum[v];} } void getsum() {for(int i = 1; i <= cc; ++i) G[fail[i]].push_back(i);dfs(0); } ll cal() {ll ans = 1LL*cc*cc;for(int i = 1; i <= cc; ++i) if(fail[i]) {int p = i, q = fail[i];while(q) q=fa[q], p = fa[p];ans -= (sum[p]-1LL);}return ans; } int main() {while(scanf("%d",&n), n) {for(int i = 1; i <= n; ++i) scanf(" %s", str), ins(str);build_ac(); getsum();printf("%lld\n", cal()); init();}return 0; }轉載于:https://www.cnblogs.com/RRRR-wys/p/9763176.html
總結
以上是生活随笔為你收集整理的HDU5129 - Yong Zheng's Death的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑中病毒后应该如何自救电脑中病毒了如何
- 下一篇: 怎么用手机登陆水星路由器怎样用手机设置水