題目描述
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
思路:暴力搜尋,三重循環,第一層是每一個的,第二層是長度,第三層是判斷
代碼:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
char name[][];
char na[][];
char str1[], str2[];
void scopy(int x, int y, char s[])
{
for(int i=; i<=x; i++)
s[i] = name[y][i];
s[x+] = '\0';
}
int main()
{
int k=;
while(scanf("%s",name[k++]) != EOF);
int i,j,l;
for(i=; i < k; i++)
{
int flag = ;
int len = strlen(name[i]);
for(j=; j<len ; j++)
{
scopy(j,i, str1);
for(l=; l<k; l++)
{
if(i == l)
continue;
else
{
scopy(j,l,str2);
if(!strcmp(str1,str2))
{
flag = ;
break;
}
}
}
if(flag)
{
flag = ;
continue;
}
if(l == k)
{
strcpy(na[i],str1);
break;
}
}
}
for(int i=; i<k; i++)
cout << name[i] << " " << na[i] << endl;
return ;
}