UVA11732 strcmp anyone --- 字典树

题解: 遍历每个单词,插入到字典树中,插入的过程中根据每个节点处的信息来计算比较次数,注意如果用指针来表示字典树的话会超时,估计是因为构造Trie的时候会遍历next数组,导致时间复杂度增加一个数量级。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 4010;

int get_index(char ch) {
    if(ch>='0'&&ch<='9') return ch-'0';
    else if(ch>='a'&&ch<='z') return 10+ch-'a';
    else return 36+ch-'A';
}

// struct Trie {
//     int cnt;
//     Trie *next[62];
//     Trie() {
//         cnt = 0;
//         for(int i = 0;i < 62;i++) next[i] = NULL;
//     }
// };

int Trie[4000010][62];
int cnt[4000010];
int tot;

// void destroy(Trie *root) {
//     if(root == NULL) return;
//     for(int i = 0;i < 62;i++)
//         destroy(root->next[i]);
//     delete root;
// }

int main() {
    int n;
    int kase = 1;
   // freopen("out.txt","w",stdout);
    while(scanf("%d",&n) != EOF && n) {
        tot = 1;
        memset(cnt,0,sizeof(cnt));
        memset(Trie,0,sizeof(Trie));
        int root = 0;
        ll ans = 0;
        for(int i = 0;i < n;i++) {
            ll temp = ans;
            char str[1010];
            scanf("%s",str);
            int cur = root;
            int len = strlen(str);
            int t = i;
            for(int j = 0;j < len;j++) {
                char ch = str[j];
                int index = get_index(ch);
                if(Trie[cur][index]==0) {
                    cnt[tot] = 1;
                    Trie[cur][index] = tot++;
                    ans += t;
                    t = 0;
                    cur = Trie[cur][index];
                } else {
                    cur = Trie[cur][index];
                    ans += cnt[cur]+t;  
                    t = cnt[cur];
                    cnt[cur]++;
                }
            }
            int tt = 0;
            for(int j = 0;j < 62;j++) {
                if(Trie[cur][j] != NULL) tt += cnt[Trie[cur][j]];
            }
            ans += (t-tt)*2+tt;
          //  printf("delta : %lld\n",ans-temp);
        }
        printf("Case %d: %lld\n",kase++,ans);

       // destroy(root);

    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值