用的是map,把相同前缀的词的概率加到一个map里面,找出里面的概率最大的,然后在相同的最大概率中找出字典序最小的.
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> #include <fstream> using namespace std; const int b[10][4]={{0},{0},{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}}; //ofstream fout("out.out"); //#define cout fout map<string,int> m; struct preWord { string word; int probability; preWord(string s="",int pro=0):word(s),probability(pro){} }; //remove elements with length less than n void remove(vector<preWord> &v,int n){ vector<preWord>::iterator it=v.begin(); for (;it!=v.end();) { if (it->word.size()<n) { it=v.erase(it); continue; } ++it; } } void removeImproper(vector<preWord> &v,char ch,int j){ vector<preWord>::iterator it=v.begin(); for (;it!=v.end();) { int i=0; int flag=0; for (;i<4;++i) { if(b[ch-'0'][i]==it->word[j]){ flag=1; } } if(!flag) it=v.erase(it); else ++it; } } string findMostProper(vector<preWord> &v,string &s){ m.clear(); vector<string> temp; vector<preWord>::iterator it=v.begin(); for (;it!=v.end();++it) { m[string(it->word.begin(),it->word.begin()+s.size())]+=it->probability; } map<string,int>::iterator mit=m.begin(); if(mit==m.end()) { return "MANUALLY"; } else{ int maxP=mit->second; for (++mit;mit!=m.end();++mit) { if (mit->second>maxP) { maxP=mit->second; } } for (mit=m.begin();mit!=m.end();++mit) { if(mit->second==maxP){ temp.push_back(mit->first); } } string min=temp[0]; for (int i=1;i<temp.size();++i) { if (temp[i]<min) { min=temp[i]; } } return min; } } int main(){ int n,c=1;; cin>>n; while (n--) { vector<preWord> dic; int dN,i=0; cin>>dN; for (;i<dN;++i) { preWord t; cin>>t.word; cin>>t.probability; dic.push_back(t); } cout<<"Scenario #"<<c++<<":"<<endl; int nS; cin>>nS; cin.ignore(1); for (i=0;i<nS;++i) { vector<preWord> cDic=dic; string str=""; int j=1; char ch; int fl=0; while (ch=cin.get(),ch!='1') { if(fl){ cout<<"MANUALLY"<<endl; continue; } remove(cDic,j); removeImproper(cDic,ch,j-1); str+=ch; string s=findMostProper(cDic,str); if(s=="MANUALLY"){fl=true;cout<<s<<endl;} else cout<<s<<endl; ++j; } cin.ignore(1); cout<<endl; } cout<<endl; } return 0; }