您的位置:首页 > 其它

UVA 11732 strcmp() Anyone?(trie)

2013-10-07 16:54 441 查看
题目大意:给你那个 strcmp 函数的内部,现在给你n个字符串,要两两比较,问你strcmp里判断总共用了几次?

思路:trie,又是Submission error,算了,先存下吧。。
代码如下(不知道对不对。。 = =):

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

typedef long long lld;

const int MAXN = 4001;

const int MAX_NODE = MAXN*1001;

const int SIGMA_SIZE = 27;

int ch[MAX_NODE][SIGMA_SIZE];

int val[MAX_NODE];

struct Trie
{
int sz;

Trie()
{
sz = 1;
val[0] = 0;
memset(ch[0],0,sizeof(ch[0]));
}

int idx(char c)
{
if(c == '\0')
return 0;
else return c - 'a' + 1;
}

void insert(char *s)
{
int u = 0;
int len = strlen(s);
for(int i = 0;i<=len;i++)
{
int c = idx(s[i]);
if(!ch[u][c])
{
memset(ch[sz],0,sizeof(ch[sz]));
val[sz] = 0;
ch[u][c] = sz++;
}
val[u]++;
u = ch[u][c];
}
}

int count(char *s)
{
int u = 0;
int len = strlen(s);
int cnt = 0;
for(int i = 0;i<=len;i++)
{
cnt += val[u];
int c = idx(s[i]);
if(!ch[u][c])
return cnt;
cnt += val[u];
u = ch[u][c];
}
return cnt;
}
};

char str[MAXN];

int main()
{
int cas = 0;
int n;
while(~scanf("%d",&n)&&n)
{
Trie tr;
lld ans = 0;
for(int i = 1;i<=n;i++)
{
scanf("%s",str);
if(i > 1) ans += tr.count(str);
//printf("ans = %d\n",ans);
tr.insert(str);
}
printf("Case %d: %lld\n",++cas,ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: