您的位置:首页 > 其它

POJ2001 Shortest Prefixes trie树模板

2012-08-30 15:03 435 查看
http://poj.org/problem?id=2001

题目大意:现在人们喜欢用缩写,比如carbon可以缩写为carb,但不能缩写为car。因为有car这个准确的单词。给你n个单词(n<=1000),每个单词长度不超过20。求出每个单词的最短缩写。

题意:先建立trie树,树上节点增加一个计数器。然后对于每个单词用trie树查找,到第一次出线计数器为1时停止输出即可。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
//const double eps=1e-7;
//const double INF=1e50;
//const double pi=acos(-1);

#define N 1005
#define M 20005

char st
[30];

struct tree
{
char ch;
vector<int> c;
int ci;
}p[M];

int check(int q,char cha)
{
for (int i=0;i<(int)p[q].c.size();i++)
if (p[p[q].c[i]].ch==cha) return p[q].c[i];

return -1;
}

int main()
{
freopen("a","r",stdin);

int i,j,l,q,num=0,n=1;
while(gets(st
))
{
l=strlen(st
);

q=0;
p[0].ci=10000;
for (i=0;i<l;i++)
{
int an=check(q,st
[i]);
if (an>-1) q=an;
else
{
num++;
p[q].c.push_back(num);

p[num].ch=st
[i];
p[num].ci=0;
q=num;
}

p[q].ci++;
}

n++;
}

for (i=1;i<n;i++)
{
printf("%s ",st[i]);
l=strlen(st[i]);

q=0;
for (j=0;j<l;j++)
{
int an=check(q,st[i][j]);
if (j==(l-1) || p[an].ci==1)
{
for (int k=0;k<=j;k++) printf("%c",st[i][k]);
printf("\n");
break;
}
else q=an;
}
}

return 0;
}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
//const double eps=1e-7;
//const double INF=1e50;
//const double pi=acos(-1);

#define N 1005
#define M 20005

char st
[30];

struct tree
{
char ch;
vector<int> c;
int ci;
}p[M];

int check(int q,char cha)
{
for (int i=0;i<(int)p[q].c.size();i++)
if (p[p[q].c[i]].ch==cha) return p[q].c[i];

return -1;
}

int main()
{
freopen("a","r",stdin);

int i,j,l,q,num=0,n=1;
while(gets(st
))
{
l=strlen(st
);

q=0;
for (i=0;i<l;i++)
{
p[q].ci++;

int an=check(q,st
[i]);
if (an>-1) q=an;
else
{
num++;
p[q].c.push_back(num);

p[num].ch=st
[i];
p[num].ci=0;
q=num;
}
}
p[q].ci++;//这里要加因为最后一个字符虽然访问了,但树节点还没开始访问,

n++;
}

for (i=1;i<n;i++)
{
printf("%s ",st[i]);
l=strlen(st[i]);

q=0;
for (j=0;j<l;j++)
{
int an=check(q,st[i][j]);
if (j==(l-1) || p[an].ci==1)
{
for (int k=0;k<=j;k++) printf("%c",st[i][k]);
printf("\n");
break;
}
else q=an;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: