1601: 名字缩写
时间限制: 1 Sec 内存限制: 128 MB
提交: 240 解决: 61
[提交][状态][讨论版]
题目描述
Noname老师有一个班的学生名字要写,但是他太懒了,想少写几个字母。很快他发现这是可行的,例如下面的学生名单:
Davidson
Davis
Dixon
Smith
可以缩写为
David
Davis
Di
S
David 指明Davidson外,不可能是其他三位同学名字的前缀。S仅能代表Smith。在确保能无歧义指明同学的前提下,Noname老师总是希望使用最少的字母。
输入
给定一系列名字,每个名字一行(不超过100行),名字仅含英文字母,名字长度不超过40,这些名字按字母升序排列, 任意两个名字不相同而且一个名字不会正好是另一个名字的前缀。
输出
每行输入对应一行输出,内容为空格分开原来的名字和缩写后的名字。
样例输入
Adams
Andersen
Anderson
Carson
Carter
Carville
Cooper
Coply
Smith
Smythe
Sorensen
Sorenson
Wynn
样例输出
Adams Ad
Andersen Anderse
Anderson Anderso
Carson Cars
Carter Cart
Carville Carv
Cooper Coo
Coply Cop
Smith Smi
Smythe Smy
Sorensen Sorense
Sorenson Sorenso
Wynn W
提示
来源
2014湖南科技大学校赛
来源: http://acm.hnust.edu.cn/JudgeOnline/problem.php?id=1601
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char A[100][40];
int cmp(const void*a,const void*b)
{
return strcmp((char *)a,(char *)b);
}
void Handle(int count)
{
int Top=0,Pre_Top=0,len=0;
for(int i=0;i<count;i++)
{
printf("%s ",A[i]);
len=strlen(A[i]);
for(Top=0;Top<len;Top++)
if(A[i][Top]!=A[i+1][Top]) break;//检索到与下串不同字符,退出循环
if(Top<Pre_Top) A[i][Pre_Top+1]='\0';//不比上一串相同字符串长
else A[i][Top+1]='\0'; //比上一串相同字符串长
Pre_Top=Top;//更新
puts(A[i]);
}
}
int main()
{
//freopen("D:\\test.txt","r",stdin);
//freopen("D:\\txxt.txt","w",stdout);
int count=0;
while(gets(A[count++])!=NULL);
count--;//多读取了一个回车,辛亏提示是格式错误 要不然一辈子也不一定找到错误
qsort(A,count,sizeof(A[0]),cmp);
Handle(count);
//for(int i=0;i<count;i++) puts(c[i]);
return 0;
}