UVa11732 - strcmp() Anyone?

Trie

#include <bits/stdc++.h>
#define sigma_size 100
#define maxnode 4000010
typedef long long ll;
using namespace std;
ll ans;
struct Trie {
    struct Node {
        int val;//记录结点字母
        int cnt;//记录节点字母出现次数
        int fir, nxt;
        void init() {
            cnt = 0;
            fir = nxt = val = -1;
        }
    };
    Node node[maxnode];
    int used, root;
    int P(char ch) {
        if ('0' <= ch && ch <= '9') return ch - '0';
        if ('a' <= ch && ch <= 'z') return 10 + ch - 'a';
        if ('A' <= ch && ch <= 'Z') return 36 + ch - 'A';
        return 62;
    }
    int newNode() {
        node[used].init();
        return used ++;
    }
    void init() {
        used = 0;
        root = newNode();
    }
    int Find(int x, int p) {
        for (int i = node[x].fir; ~i; i = node[i].nxt) {
            if (node[i].val == p) return i;
        }
        return -1;
    }
    void Add(char *s) {
        int x = root;
        for (int i = 0; ; ++ i) {
            int p = P(s[i]);
            int ix = Find(x, p);
            if (ix == -1) {
                ix = newNode();
                node[ix].val = p;
                node[ix].nxt = node[x].fir;
                node[x].fir = ix;
            }
            ans += node[x].cnt - node[ix].cnt;
            ans += node[ix].cnt << 1;
            ++node[x].cnt;
            x = ix;
            if (s[i] == '\0') break;
        }
        ++ node[x].cnt;
    }
}tx;
char tmp[1010];
int main() {
    #ifdef LOCAL
        freopen("data.in", "r", stdin);
    #endif // LOCAL
    int n, now = 0;
    while (scanf("%d", &n) != EOF) {
        tx.init();
        if (n == 0) break;
        ans = 0;
        for (int i = 0; i < n; ++ i) {
            scanf("%s", tmp);
            tx.Add(tmp);
        }
        printf("Case %d: ", ++ now);
        cout << ans << endl;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值