Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 8118 | Accepted: 3445 |
Description
In the sample input below, "carbohydrate" can be abbreviated to "carboh", but it cannot be abbreviated to "carbo" (or anything shorter) because there are other words in the list that begin with "carbo".
An exact match will override a prefix match. For example, the prefix "car" matches the given word "car" exactly. Therefore, it is understood without ambiguity that "car" is an abbreviation for "car" , not for "carriage" or any of the other words in the list that begins with "car".
Input
Output
#include<stdio.h>
#include<string.h>
#define max 26
#define maxn1 1001
#define maxn2 30
char as[maxn1][maxn2],tt[maxn2];
struct node//初始tire樹
{
int num,k;//標記是否爲相同前綴最後字符
node *next[max];//後繼結點
} * root;
void insert(char ss[])//插入操作
{
int i,j;
node *p=root,*t;//p指向當前節點,t用來開闢內存
for(i=0;ss[i];i++)//將每個字符存起來的過程
{
if(p->next[ss[i]-'a']==NULL)//當p指向爲空的時候,需要開闢新的節點
{
t=new node;
t->k = t->num = 0;
for(j=0;j<max;j++)
t->next[j]=NULL;
p->next[ss[i]-'a']=t;//接上新的節點
}
p->k++;
p=p->next[ss[i]-'a'];//p指向下一個節點
p->num++;//
}
}
void search(char ss[])//查找
{
node *p=root;//p指向根節點
int t=0;
for(int i=0;ss[i];i++)
{
p=p->next[ss[i]-'a'];//p指向下一結點
if(p->num>1)
{
tt[t]=ss[i];
t++;
}
if(p->num==1)
{
tt[t]=ss[i];
tt[t+1]='\0';
return;
}
}
if(p->k == 1) tt[t]='\0';
tt[t]='\0';//這個是防止上面的p->num都是大於1的
return ;
}
int main()
{
int l = 0,i,j;
char s[maxn2];
root = new node;
root->k = root->num = 0;
for(j=0;j<max;j++)
root->next[j]=NULL;
while(scanf("%s",s) != EOF) {
//if (s[0] == '0') break;
strcpy(as[l++],s);
insert(s);
}
for(i = 0;i < l;i++) {
search(as[i]);
printf("%s %s\n",as[i],tt);
}
//scanf("%d",&i);
return 0;
}