HDU 5880 Family View
$AC$自动机。
用$AC$自动机匹配一次,开一个$flag$记录一下以$i$位置为结尾的最长要打$*$多少个字符,然后倒着扫描一次就可以输出了。
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #include<stack> #include<bitset> #include<iostream> using namespace std; typedef long long LL; const double pi=acos(-1.0),eps=1e-6; void File() { freopen("D:\\in.txt","r",stdin); freopen("D:\\out.txt","w",stdout); } template <class T> inline void read(T &x) { char c=getchar(); x=0; while(!isdigit(c)) c=getchar(); while(isdigit(c)) {x=x*10+c-'0'; c=getchar();} } const int maxn=1000010; int flag[maxn]; char buf[maxn]; struct Trie { int next[maxn][26],fail[maxn],end[maxn],Len[maxn]; int root,L; int newnode() { for(int i = 0;i < 26;i++) next[L][i] = -1; Len[L]= end[L] = 0; L++; return L-1; } void init() { L = 0; root = newnode(); } void insert(char buf[]) { int len = strlen(buf); int now = root; for(int i = 0;i < len;i++) { if(next[now][buf[i]-'a'] == -1) next[now][buf[i]-'a'] = newnode(); now = next[now][buf[i]-'a']; } end[now]++; Len[now]=strlen(buf); } void build() { queue<int>Q; fail[root] = root; for(int i = 0;i < 26;i++) if(next[root][i] == -1) next[root][i] = root; else { fail[next[root][i]] = root; Q.push(next[root][i]); } while( !Q.empty() ) { int now = Q.front(); Q.pop(); for(int i = 0;i < 26;i++) if(next[now][i] == -1) next[now][i] = next[fail[now]][i]; else { fail[next[now][i]]=next[fail[now]][i]; Q.push(next[now][i]); } } } void query(char buf[]) { int len = strlen(buf); int now = root; int res = 0; for(int i = 0;i < len;i++) { int sign; if(buf[i]>='A'&&buf[i]<='Z') sign=buf[i]-'A'; else if(buf[i]>='a'&&buf[i]<='z') sign=buf[i]-'a'; else { now=root; continue; } now = next[now][sign]; int temp = now; while( temp != root ) { flag[i]=max(flag[i],Len[temp]); temp = fail[temp]; } } } }; Trie ac; int main() { int T,n; scanf("%d",&T); while( T-- ) { scanf("%d",&n); ac.init(); for(int i = 0;i < n;i++) { scanf("%s",buf); ac.insert(buf); } ac.build(); getchar(); gets(buf); memset(flag,0,sizeof flag); ac.query(buf); int leng=strlen(buf); int num=0; for(int i=leng-1;i>=0;i--) { num=max(num,flag[i]); if(num==0) continue; else buf[i]='*', num--; } printf("%s\n",buf); } return 0; }