HDU 3065(AC自動機)

Problem Description
小t非常感謝大家幫忙解決了他的上一個問題。然而病毒侵襲持續中。在小t的不懈努力下,他發現了網路中的“萬惡之源”。這是一個龐大的病毒網站,他有着好多好多的病毒,但是這個網站包含的病毒很奇怪,這些病毒的特徵碼很短,而且只包含“英文大寫字符”。當然小t好想好想爲民除害,但是小t從來不打沒有準備的戰爭。知己知彼,百戰不殆,小t首先要做的是知道這個病毒網站特徵:包含多少不同的病毒,每種病毒出現了多少次。大家能再幫幫他嗎?

Input
第一行,一個整數N(1<=N<=1000),表示病毒特徵碼的個數。
接下來N行,每行表示一個病毒特徵碼,特徵碼字符串長度在1—50之間,並且只包含“英文大寫字符”。任意兩個病毒特徵碼,不會完全相同。
在這之後一行,表示“萬惡之源”網站源碼,源碼字符串長度在2000000之內。字符串中字符都是ASCII碼可見字符(不包括回車)。

Output
按以下格式每行一個,輸出每個病毒出現次數。未出現的病毒不需要輸出。
病毒特徵碼: 出現次數
冒號後有一個空格,按病毒特徵碼的輸入順序進行輸出。

Sample Input

3
AA
BB
CC
ooxxCC%dAAAoen....END

Sample Output

AA: 2
CC: 1

Hint
Hit:
題目描述中沒有被提及的所有情況都應該進行考慮。比如兩個病毒特徵碼可能有相互包含或者有重疊的特徵碼段。
計數策略也可一定程度上從Sample中推測。

解題思路:AC自動機模板,但是需要用一個數組記錄這個節點是第幾個字符串的路徑的終點,然後再跑到該節點時,將其所代表的的字符串所表示的答案++既可以啦。

代碼:

#pragma GCC optimize(2)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <bitset>
#include <queue>
//#include <random>
#include <time.h>
using namespace std;
#define int long long
#define ull unsigned long long
#define ls root<<1
#define rs root<<1|1
const int inf=1ll*1<<60;
const int maxn=5e4+10;
const int maxm=1e6+10;
int to[maxn][27],cnt[maxn];
int tot,fail[maxn],id[maxn],ans[1100];
char arr[maxm<<1],str[1010][60];
void add(char *s,int k) {
    int now=0;
    for(int i=0; s[i]!='\0'; i++) {
        int x=s[i]-'A';
        if(!to[now][x])
            to[now][x]=++tot;
        now=to[now][x];
    }
    id[now]=k;
    cnt[now]++;
}
void getfail() {
    queue<int> q;
    for(int i=0; i<26; i++) {
        if(to[0][i])
            q.push(to[0][i]);
    }
    while(!q.empty()) {
        int x=q.front();
        q.pop();
        for(int i=0; i<26; i++) {
            if(to[x][i])
                fail[to[x][i]]=to[fail[x]][i],q.push(to[x][i]);
            else
                to[x][i]=to[fail[x]][i];
        }
    }
}
void query(char *s) {
    int now=0;
    for(int i=0; s[i]!='\0'; i++) {
        if(s[i]<'A' || s[i]>'Z') {
            now=0;
            continue;
        }
        int x=s[i]-'A';
        now=to[now][x];
        for(int j=now; j; j=fail[j]) {
            if(cnt[j]) {
                ans[id[j]]+=cnt[j];
            }
        }
    }
}
signed main() {
    int n;
    while(~scanf("%lld",&n)) {
        memset(to,0,sizeof to);
        memset(fail,0,sizeof fail);
        memset(cnt,0,sizeof cnt);
        memset(id,0,sizeof id);
        memset(ans,0,sizeof ans);
        tot=0;
        for(int i=1; i<=n; i++) {
            scanf("%s",str[i]);
            add(str[i],i);
        }
        scanf("%s",arr);
        getfail();
        query(arr);
        for(int i=1; i<=n; i++) {
            if(ans[i]) {
                printf("%s: %lld\n",str[i],ans[i]);
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章