ZOJ1038

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1038

同样,抄答案。

整体思路就是按照按键的顺序,构造出一些单词,如果构造出的单词是词典中的单词或者是词典中某些单词的前缀,那么久把构造出的新单词保存到words数组里,当接收到下一个按键时,就从words中枚举每一个单词,与所按得数字键上的所有字母逐一配对,组成新单词,再判断是否是字典中的单词或前缀,保存在words中,再读取下一个按键。

对于每一次按键之后,所生成的满足条件的单词有哪些是确定的,当读取一次按键时,都只用到上一次按键 构造出的,所以用到了类似与滚动数组的一个空间优化,用words保留上一次按键构造出的所有单词,每读取一次按键构造出的新单词暂时保存在数组newWords中,当本次按键构造完毕,就把newWords中的单词转移到word中,为下一次按键的构造单词提供初始数据。

#include<iostream>

using namespace std;

const string press[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
const int maxn = 101;

struct node
{
    string word;
    int prob;
};
node dic[1001];
node words[maxn];
int dicNum;

int check(string str)
{
    int sum = 0;
    for (int i=0; i<dicNum; i++)
        if (dic[i].word.substr(0,str.size()) == str)
            sum += dic[i].prob;
    return sum;
}

void Search(string input)
{
    node newWords[maxn];
    int total = 1;
    int newTotal;

    for (int i=0; i<input.size(); i++)
    {
        newTotal = 0;
        for (int j=0; j<total; j++)
        {
            for (int k=0; k<press[input[i] - '0'].size(); k++)
            {
                string temp = words[j].word + press[input[i] - '0'][k];
                int mark = check(temp);
                if (mark)
                {
                    newWords[newTotal].word = temp;
                    newWords[newTotal].prob = mark;
                    newTotal++;
                }
            }
        }
        int best = 0, bestid;
        for (int i=0; i<newTotal; i++)
        {
            if (newWords[i].prob > best)
            {
                best = newWords[i].prob;
                bestid = i;
            }
        }
        if (best == 0)
            cout<<"MANUALLY"<<endl;
        else
            cout<<newWords[bestid].word<<endl;
        for (int i=0; i<newTotal; i++)
            words[i] = newWords[i];
        total = newTotal;
    }
}

int main()
{
    int iCase;

    cin>>iCase;
    for (int Case=1; Case<=iCase; Case++)
    {
        cout<<"Scenario #"<<Case<<":"<<endl;
        cin>>dicNum;
        for (int i=0; i<dicNum; i++)
            cin>>dic[i].word>>dic[i].prob;
        string input;
        int m;
        cin>>m;
        for (int i=0; i<m; i++)
        {
            cin>>input;
            input = input.substr(0,input.size() - 1);
            words[0].word = "";
            words[0].prob = 0;
            Search(input);
            cout<<endl;
        }
        cout<<endl;
    }

    return 0;
}


你可能感兴趣的:(ZOJ1038)