HDU1113 POJ1318 UVA642 ZOJ1181 UVALive5328 Word Amalgamation【MAP+排序+水題】
阿新 • • 發佈:2019-02-14
Time Limit:1000MS | Memory Limit:10000K |
Total Submissions:9395 | Accepted:4498 |
Description
In millions of newspapers across the United States there is a word game called Jumble. The object of this game is to solve a riddle, but in order to find the letters that appear in the answer it is necessary to unscramble four words. Your task is to write a program that can unscramble words.Input
Output
Sample Input
tarp given score refund only trap work earn course pepper part XXXXXX resco nfudre aptr sett oresuc XXXXXX
Sample Output
score ****** refund ****** part tarp trap ****** NOT A VALID WORD ****** course ******
Source
問題描述:參見上文。
問題分析:
這是一個字典問題,自然用map來實現。問題在於還需要轉個彎,不然會掉進陷阱裡去的。
查字典問題,通常是單詞按照字典順序存放,然後將要查的單詞拆成字母,按單詞的字母順序去查字典。然而要是這樣做程式的邏輯就太零碎繁雜了。
於是,把單詞中的字元排個順序作為關鍵字,來查單詞的話就方便了。需要注意的一點,不同的單詞有可能具有相同的關鍵字。
程式說明:
這個程式的關鍵有容器類map的使用,演算法庫<algorithm>中函式sort()的使用。
這個程式未必是最佳做法,使用map<string vector<string>>作為字典也許是最佳的做法。
AC的C++語言程式如下:
/* HDU1113 POJ1318 UVA642 ZOJ1181 UVALive5328 Word Amalgamation */
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
map<string, string> dic;
string word, key;
while(cin >> word && word != "XXXXXX") {
key = word;
sort(key.begin(), key.end());
dic[word] = key;
}
while(cin >> key && key != "XXXXXX") {
sort(key.begin(), key.end());
bool flag = true;
for(map<string, string>::iterator it=dic.begin(); it!=dic.end(); it++) {
if(it->second == key) {
cout << it->first << endl;
flag = false;
}
}
if(flag)
cout << "NOT A VALID WORD" << endl;
cout << "******" << endl;
}
return 0;
}