UVA11732 字典树



刘汝佳的训练指南上的题目,见识了左儿子右兄弟的存储方式。

代码如下:

#include <cstdio>
#include <cstring>
#include <cstring>
using namespace std;

const int maxn = 4000*1000 + 10;
const int sigma_size = 26;
const int maxL = 1000+10;
int n;
int head[maxn]; //第i个节点左儿子编号
int Next[maxn]; //第i个节点右兄弟编号
char ch[maxn]; //第i个节点的字符
int tot[maxn]; //第i个节点为根的子树包含的叶子节点总数
int sz; //节点总数
long long ans ; //答案
char word[maxn];

inline void Clear(){
    sz = 1;
    tot[0] = head[0] = Next[0] = 0;
    //初始只有根节点
}

void Insert(const char *s){
    int u = 0, len = strlen(s), v;
    bool found;
    tot[0]++;

    for (int i=0; i<=len; i++) {
        found = 0;
        for (v = head[u]; v!=0; v = Next[v]){
            if (ch[v]==s[i]) {
                found = 1;
                break;
            }
        }

        if (!found){
            v = sz++;
            tot[v] = 0;
            ch[v] = s[i];
            Next[v] = head[u];
            head[u] = v;
            head[v] = 0;
        }
        u = v;
        tot[u]++;
    }
}

void init(){
    Clear();
    for (int i=1; i<=n; i++) {
        scanf("%s",word);
        Insert(word);
    }
    ans = 0;
}

void dfs(int depth, int u){
    if (head[u]==0) {
        ans += tot[u]*(tot[u]-1)*depth;
    }
    else {
        int sum = 0;
        for (int v = head[u]; v!=0; v = Next[v]) sum += tot[v]*(tot[u]-tot[v]);
        ans += sum/2*(2*depth+1);

        for (int v = head[u]; v!=0; v = Next[v]) dfs(depth+1,v);
    }
}

int kase = 0;
int main(){
    while (scanf("%d",&n) && n){
        init();
        dfs(0,0);
        printf("Case %d: %lld\n",++kase,ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值