1. 程式人生 > >HDU1113 POJ1318 UVA642 ZOJ1181 UVALive5328 Word Amalgamation【MAP+排序+水題】

HDU1113 POJ1318 UVA642 ZOJ1181 UVALive5328 Word Amalgamation【MAP+排序+水題】

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

The input contains four parts: 1) a dictionary, which consists of at least one and at most 100 words, one per line; 2) a line containing XXXXXX, which signals the end of the dictionary; 3) one or more scrambled 'words' that you must unscramble, each on a line by itself; and 4) another line containing XXXXXX, which signals the end of the file. All words, including both dictionary words and scrambled words, consist only of lowercase English letters and will be at least one and at most six characters long. (Note that the sentinel XXXXXX contains uppercase X's.) The dictionary is not necessarily in sorted order, but each word in the dictionary is unique.

Output

For each scrambled word in the input, output an alphabetical list of all dictionary words that can be formed by rearranging the letters in the scrambled word. Each word in this list must appear on a line by itself. If the list is empty (because no dictionary words can be formed), output the line "NOT A VALID WORD" instead. In either case, output a line containing six asterisks to signal the end of the list.

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;
}