题意:求给出的字符串的最小前缀,此前缀满足是这些字符串中唯一的前缀,也就是这个前缀除了这个字符串以外不能再是其它字符串的前缀了.
思路:trie
这道题让我明晰了 strncpy()这个函数,它是把第二个字符串的前n个字符附给第一个字符串,但是我输出的时候却错了,可能第n个字符没有被覆盖,后来在第一个字符串的n这个位置改成'\0'...果断水过.
#include<iostream>
#include<cstring>
using namespace std;
struct node
{
int count;
node *next[26];
node()
{
count=0;
for(int i=0;i<26;i++)
next[i]=NULL;
}
};
char s[30];
void insert(node *root,char *word)
{
int i=0,branch;
node *l=root;
while(word[i]!='\0')
{
branch=word[i]-'a';
if(l->next[branch]!=NULL)
{
l->next[branch]->count++;
//printf("insertcount=%d\n",l->next[branch]->count);
}
else l->next[branch]=new node();
l=l->next[branch];
i++;
}
}
int search(node *root,char *word)
{
int i=0,branch,ans;
node *l=root;
while(word[i]!='\0')
{
branch=word[i]-'a';
if(l->next[branch]!=NULL)
{
//printf("count=%d\n",l->next[branch]->count);
l=l->next[branch];
if(l->count==0)
{ans=i;break;}
}
i++;
}
if(word[i]=='\0') strcpy(s,word);
else
{strncpy(s,word,ans+1);s[ans+1]='\0';}
return 0;
}
int main()
{
char word[30];
char str[1010][30];
node *root=new node();
int i=0;
freopen("data.txt","r",stdin);
freopen("shuchu.txt","w",stdout);
while(gets(word))
{
strcpy(str[i],word);
insert(root,word);
i++;
}
for(int j=0;j<i;j++)
{
//printf("search=%s\n",str[j]);
search(root,str[j]);
printf("%s %s\n",str[j],s);
}
return 0;
}