UVA “strcmp()" Anyone?【字典树数组链表版】

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值