UVA “strcmp()" Anyone?【字典樹數組鏈表版】

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/zehong1995/article/details/78345375

UVA “strcmp()” Anyone?

題意:

這裏寫圖片描述
Sample Input
2
a
b
4
cat
hat
mat
sir
0
Sample Output
Case 1: 1
Case 2: 6

題目鏈接:

https://odzkskevi.qnssl.com/d53d2ae0b0fc885d7fb0af4dcea1489e?v=1508641012

#include <bits/stdc++.h>
using namespace std;
const int maxn = 4e6 + 10;
long long ans;
struct Trie {
    char ch[maxn];//第i結點的字符
    int tot[maxn];//包括第i結點子結點數
    int lch[maxn];//左孩子編號
    int nxt[maxn];//兄弟結點鏈表
    int sz = 1;
    void clear() {
        sz = 1;
        ch[0] = tot[0] = lch[0] = nxt[0] = 0;
    }
    void insert(char *s) {
        int u = 0, v, len = strlen(s);
        for(int i = 0; i <= len; ++ i) {
            for(v = lch[u]; v; v = nxt[v]) {
                if(ch[v] == s[i]) break;
            }

            if(v == 0) {
                v = sz++;
                tot[v] = 0;
                ch[v] = s[i];
                nxt[v] = lch[u];
                lch[u] = v;
                lch[v] = 0;
            }
            ans += (tot[u] - tot[v]) * (2 * i + 1);
            if(i == len) {
                ans += tot[v] * (2 * i + 2); //最後一個字符'\0',所以這種情況是字符串相同的情況
            }
            tot[u]++;
            u = v;
        }
        tot[u]++; //忘了最後一個字符
    }
}trie;
int main() {
    int n;

    int cas = 1;
    while(~scanf("%d", &n) && n) {
        trie.clear();
        ans = 0;
        char str[1100];
        while(n--) {
            scanf("%s", str);
            trie.insert(str);
        }
        printf("Case %d: %lld\n", cas++, ans);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章