【bzoj1195】[HNOI2006]最短母串 AC自动机+状态压缩+BFS最短路
生活随笔
收集整理的這篇文章主要介紹了
【bzoj1195】[HNOI2006]最短母串 AC自动机+状态压缩+BFS最短路
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文地址:http://www.cnblogs.com/GXZlegend/p/6825226.html
題目描述
給定n個字符串(S1,S2,?,Sn),要求找到一個最短的字符串T,使得這n個字符串(S1,S2,?,Sn)都是T的子串。
輸入
第一行是一個正整數n(n<=12),表示給定的字符串的個數。以下的n行,每行有一個全由大寫字母組成的字符串。每個字符串的長度不超過50.
輸出
只有一行,為找到的最短的字符串T。在保證最短的前提下,如果有多個字符串都滿足要求,那么必須輸出按字典序排列的第一個。
樣例輸入
2
ABCD
BCDABC
樣例輸出
ABCDABC
題解
AC自動機+BFS
先求出fail數組和Trie圖,同時標記每個位置是哪些字符串的結尾,用二進制儲存。
要求包含所有串的最小長度,需要記錄當前包含哪些串,需要狀壓。
當到達字符串結尾時,更改狀態。
所以Trie圖可以看成一個分層圖,所求為0,1到(1<<n)-1,i的最短路。
由于每條路徑代表一個字符,所以邊權為1,可以使用BFS求最短路得解。
#include <cstdio> #include <cstring> char str[60] , ch[610] , ans[610]; int tot = 1 , next[610][26] , fail[610] , val[610] , qx[1500010] , qy[1500010] , l , r , dis[610][4096] , fromp[610][4096]; void build() {int x , i;for(i = 0 ; i < 26 ; i ++ ) next[0][i] = 1;l = r = 1 , qx[1] = 1;while(l <= r){x = qx[l ++ ];for(i = 0 ; i < 26 ; i ++ ){if(next[x][i])fail[next[x][i]] = next[fail[x]][i] , val[next[x][i]] |= val[fail[next[x][i]]] , qx[++r] = next[x][i];else next[x][i] = next[fail[x]][i];}} } int main() {int n , l , i , j , x , y;scanf("%d" , &n);for(i = 1 ; i <= n ; i ++ ){scanf("%s" , str + 1) , l = strlen(str + 1) , x = 1;for(j = 1 ; j <= l ; j ++ ){if(!next[x][str[j] - 'A']) next[x][str[j] - 'A'] = ++tot;x = next[x][str[j] - 'A'] , ch[x] = str[j];}val[x] |= 1 << (i - 1);}build();memset(dis , -1 , sizeof(dis));l = r = 1 , qx[1] = 1 , qy[1] = 0 , dis[1][0] = 0;while(l <= r){x = qx[l] , y = qy[l];for(i = 0 ; i < 26 ; i ++ ){int tx = next[x][i] , ty = y | val[tx];if(dis[tx][ty] == -1){dis[tx][ty] = dis[x][y] + 1 , fromp[tx][ty] = l;if(ty == (1 << n) - 1){int px = tx , py = ty , tmp;for(i = dis[tx][ty] ; i ; i -- )ans[i] = ch[px] , tmp = fromp[px][py] , px = qx[tmp] , py = qy[tmp];printf("%s\n" , ans + 1);return 0;}qx[++r] = tx , qy[r] = ty;}}l ++ ;}return 0; }?
轉載于:https://www.cnblogs.com/GXZlegend/p/6825226.html
總結
以上是生活随笔為你收集整理的【bzoj1195】[HNOI2006]最短母串 AC自动机+状态压缩+BFS最短路的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 截图工具当前未在计算机运行
- 下一篇: 知识图谱-资源收集