POJ 1318

题意:给出一个字典和一些单词A,请找出字典中所有的单词B,使得B可通过变换其中字母的顺序变成A的。按字典序输出单词B

思路:对每个单词先内排序,也就是将单词本身变成一个升序单词,再对字典排序。最后用O(n)的方法判断所需的单词是否在字典中

16ms

 

#include <iostream> #include <algorithm> #include <string> #define F(i,a,b) for (int i=a;i<=b;i++) using namespace std; struct Node { string word; int a[6], len; Node () {} Node(string str) { word = str; len = str.length(); F(i,0,len-1) a[i] = str[i] ; sort( &a[0], &a[ len ] ); } bool operator < (const Node& b) const { F(i,0, len-1 ) { if (a[i] < b.a[i] ) return true; else if (a[i] > b.a[i]) return false; } if (b.len > len ) return false; return (word < b.word ); } bool operator == (const Node& b) const { if (len!= b.len ) return false; F(i,0,len-1) if (a[i] != b.a[i]) return false; return true; } }; Node dic[101]; int ndic; int main() { string str; while (cin >> str && str != "XXXXXX") dic[ ++ndic ] = Node(str) ; // init sort(&dic[1], &dic[ ndic+1 ] ); while (cin >> str && str != "XXXXXX") { Node w = Node(str); int total = 0; F(i,1,ndic) if ( dic[i] == w ) { cout << dic[i].word << endl; total++; } if ( total ) cout << "******/n"; else cout << "NOT A VALID WORD/n******/n"; } return 0; }

 

 

你可能感兴趣的:(POJ 1318)