uva 1401 Remember the Word ( Trie + DP ),1401trie

來源:互聯網
上載者:User

uva 1401 Remember the Word ( Trie + DP ),1401trie

題意:給出n(n<=4000)個單詞和一個字串(len<=300000),求把這個字串分解成若干個單詞的拼接,有多少種方法

思路:Trie,先把單詞建成Trie,然後進行dp,dp[i]表示以字串中第i個字母為開頭的情況,然後每個狀態只要在Trie樹上找到相應的字母開頭的單詞,然後dp[i] = sum{dp[i + len(x)]}進行狀態轉移即可 這個x是n個單詞中的一個,可以用Trie查詢


code:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 300005;const int MOD = 20071027;int ch[maxn][26];int val[maxn];int sz;int idx(char c){return c-'a';}void insert(char* s){    int u = 0;    int len = strlen(s);    for(int i = 0; i < len; i++){        int c = idx(s[i]);        if(!ch[u][c]){            memset(ch[sz], 0, sizeof(ch[sz]));            val[sz] = 0;            ch[u][c] = sz++;        }        u = ch[u][c];    }    val[u] = 1;}void init(){    sz = 1;    memset(ch[0],0,sizeof(ch[0]));    int m;    scanf("%d",&m);    char str[105];    while(m--){        scanf("%s",str);        insert(str);    }}int d[maxn];void find(int id, char* s){    d[id] = 0;    int u = 0;//    int len = strlen(s);    for(int i = id; s[i]; i++){        int c = idx(s[i]);        if(!ch[u][c]) return;        u = ch[u][c];        if(val[u]) d[id] = (d[id]+d[i+1])%MOD;    }}void solve(char* s){    int len = strlen(s);    d[len] = 1;    for(int i = len-1; i >= 0; i--){        find(i, s);    }    printf("%d\n",d[0]);}int main(){    int cas = 0;    char s[maxn];    while(scanf("%s",s) != EOF){        init();        printf("Case %d: ",++cas);        solve(s);    }    return 0;}

注意:

find 函數中千萬不能strlen();不然逾時T_T。。因為每次調用都會求一次長度,時間複雜度是0(N*N);


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.