uva_11732_"strcmp()" Anyone?(字典树)

"strcmp()" Anyone?
Time Limit: 2000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu

Submit Status

Description

uva_11732_"strcmp()" Anyone?(字典树)_第1张图片

uva_11732_"strcmp()" Anyone?(字典树)_第2张图片

uva_11732_"strcmp()" Anyone?(字典树)_第3张图片uva_11732_"strcmp()" Anyone?(字典树)_第4张图片


题意:对给定的字符串,问任意两个字符串进行strcmp()函数语句一共执行了几次。

分析:字典树问题,边插入边统计。可以想到的是,如果两个字符串不相同,那么一定是奇数次;如果两个字符串完全相同,那么则是这两个单词比较次数是偶数即2*(len+1)次;而处理两个单词是完全相同,则在字典树加一个tail标记结尾即可,并可直接使用tail统计结尾个数以便于计算比较次数。此题数据量比较大,用指针操作字典树超时了,改成结构体数组过了,还有uva用%lld!切记!切记!!!

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=28438

代码清单:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<ctime>
#include<cctype>
#include<string>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;

typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;

const int maxn = 70;
const int maxs = 1000 + 5;
const int maxt = 4100000 + 5;

struct Trie{
    int data;
    int tail;
    int next[maxn];
}trie[maxt];

int number;
int n,cases;
char str[maxs];
ll ans;

void init(){
    number=0;
    memset(trie,0,sizeof(trie));
}

int get_idx(char ss){
    int pose;
    if(ss>='0'&&ss<='9') pose=ss-'0';
    else if(ss>='A'&&ss<='Z') pose=ss-'A'+10;
    else pose=ss-'a'+36;
    return pose;
}

ll createTrie(char *s){
    int len=strlen(s),idx;
    int j=0;
    ll sum=0;
    for(int i=0;i<len;i++){
        idx=get_idx(s[i]);
        if(trie[j].next[idx]){
            j=trie[j].next[idx];
            sum+=trie[j].data;
            trie[j].data++;
        }
        else{
            trie[j].next[idx]=++number;
            j=number;
            trie[j].data=1;
            trie[j].tail=0;
        }
    }
    sum=2*sum;
    if(trie[j].tail){
        sum+=trie[j].tail;
        trie[j].tail++;
    }
    else trie[j].tail=1;
    return sum;
}

void input(){
    ans=n*(n-1)/2;
    for(int i=0;i<n;i++){
        scanf("%s",str);
        ans+=createTrie(str);
    }
}

void solve(){
    printf("Case %d: %lld\n",++cases,ans);
}

int main(){
    cases=0;
    while(scanf("%d",&n)!=EOF&&n){
        init();
        input();
        solve();
    }
}


你可能感兴趣的:(Algorithm,ACM,uva,trie)