题意:输入纯英文单词文本(单词间可隔一个或多个空格且单词不会在行间断开输入),输入以#结束。在文本中寻找这样的单词(relative ananagram):在文本中没有该单词的各字母经过重新排列后得到的单词(不论字母大小写)。最后将这样的单词按字典序一个一行地输出。
边输入边标记这样的单词效率会高些。
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<algorithm>
using namespace std;
const int maxn=1000000;
char word[maxn][30];
int p[maxn],t[30];
struct Ran{
char r[30];
};
Ran ran[maxn];
bool cmp(Ran a,Ran b){
return strcmp(a.r,b.r)<0;
}
int main()
{
int n=0,i=0;
char c;
memset(p,0,sizeof(p));
while(c=getchar()){
if(c=='#') break;
if(isalpha(c)){
word[n][i++]=c;
}
else if(!isalpha(c)&&i){
word[n][i]='\0';
for(int j=n-1;j>=0;j--){
int len=strlen(word[j]);
if(len==i&&len!=1){
memset(t,0,sizeof(t));
int count=0;
for(int x=0;x<i;x++){
for(int y=0;y<len;y++){
if(toupper(word[n][x])==toupper(word[j][y])&&!t[y]){
t[y]=1;
count++;
break;
}
}
}
if(count==i){
p[j]=p[n]=1;
}
}
}
n++; i=0;
}
}
i=0;
for(int j=0;j<n;j++){
if(!p[j]) strcpy(ran[i++].r,word[j]);
}
sort(ran,ran+i,cmp);
for(int j=0;j<i;j++)
printf("%s\n",ran[j].r);
return 0;
}
--------------------------------------------------------------------------------------------
Keep It Simple,Stupid!
--------------------------------------------------------------------------------------------