题目:给你一个单词列表。再给你一些新的单词。输出列表中又一次排列能得到此新单词的词。

分析:字符串。对每一个字符串的字母排序生成新的传f(str)。总体排序,用二分来查找就可以。

说明:注意输出要满足字典序,先排序后查找。

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio> using namespace std; typedef struct wnode
{
char word[7];
char abcd[7];
}words;
words W[101]; int cmp(words a, words b)
{
int c = strcmp(a.abcd, b.abcd);
if (c != 0) return c<0;
return strcmp(a.word, b.word)<0;
} int bs(char str[], int r)
{
int l = 0,m,c;
while (l < r) {
m = (l+r)/2;
c = strcmp(W[m].abcd, str);
if (c < 0)
l = m+1;
else r = m;
}
return l;
} char buf[7]; int main()
{
int count = 0;
while (gets(W[count].word) && strcmp(W[count].word, "XXXXXX")) {
strcpy(W[count].abcd, W[count].word);
sort(W[count].abcd, W[count].abcd+strlen(W[count].abcd));
count ++;
} sort(W, W+count, cmp); while (gets(buf) && strcmp(buf, "XXXXXX")) {
sort(buf, buf+strlen(buf));
int s = bs(buf, count-1),flag = 0;
while (!strcmp(buf, W[s].abcd)) {
printf("%s\n",W[s ++].word);
flag = 1;
}
if (!flag)
printf("NOT A VALID WORD\n");
printf("******\n");
}
return 0;
}

05-21 07:08