本题实质是对智能英语单词输入法的模拟,开门见山,题目的主要的思想就是 bfs (广度优先搜索),然后选择一种数据结构,这快推荐用 字典树 ,我用了 stl 中的优先队列,自己写太麻烦,stl 好用。
对每个序列产生,存入优先队列的头总是当前最优的单词,然后将其打印,具体代码如下:
#include <iostream> #include <stdio.h> #include <queue> #include <vector> #include <string.h> #define Maxsize 1000 using namespace std; typedef struct PHtree { int W; bool ISW; PHtree *child[26]; PHtree () { W = 0; ISW = false; for( int i = 0; i < 26; i++ ) child[i] = NULL; } }PH; typedef struct Priority_Queue_Node { PH *NOW; string word; int weight; char ch; bool operator<(const Priority_Queue_Node& node)const { if( weight == node.weight ) { if(strcmp(word.c_str() , node.word.c_str() ) < 0) return false; else return true; } return weight < node.weight; } }PQ; class cmp { public: bool operator()( const Priority_Queue_Node & n1, const Priority_Queue_Node & n2) const { return n1<n2; } }; priority_queue<Priority_Queue_Node,vector<Priority_Queue_Node>,cmp> Q; PQ p; vector<PQ> TempQ; void Loction( int t , int &Large, int &Small ) { if( t < 7 ) { Small = ( t - 2 ) * 3; Large = Small + 2; return ; } if (t == 7 ) { Small = 15; Large = 18; } if( t == 8 ) { Small = 19; Large = 21; return ; } if( t == 9 ) { Small = 22; Large = 25; return ; } } void insert( char *Pword, int Weight ,PH * & T ) { int len = strlen( Pword ); PH *now = T; for( int i = 0; i < len; i++ ) { if( now->child[ Pword[i] - 'a' ] != NULL ) now = now->child[ Pword[i] - 'a' ]; else now = now->child[ Pword[i] - 'a' ] = new PH(); now->W += Weight; } } void search ( char *Pcode, PH *T ) { int len = strlen( Pcode ); PH *Senow = T; int Large, Small; for( int i = 0; Pcode[i] != '1'; i++ ) { int mark = 0; int size = Q.size(); Loction( Pcode[i] - '0', Large, Small ); for(int j = 0 ; j < size ; j ++) { Senow = Q.top().NOW; for( int j = Small; j <= Large; j++ ) { p.word = ""; if( Senow->child[j] != 0 ) { mark = 1; p.NOW = Senow->child[j]; p.ch = 'a' + j; p.weight = Senow->child[j]->W; char temp = 'a' + j; p.word = Q.top().word +temp; TempQ.push_back( p ); } } Q.pop(); } if(mark) { int Size = TempQ.size(); for(int j = 0 ; j < Size; j++ ) { Q.push( TempQ.back() ); TempQ.pop_back(); } cout << Q.top().word << endl; } else printf("MANUALLY/n"); } } int main () { int t; int d = 1; scanf( "%d", &t ); while( t-- ) { int n , m; char PWord[104], PCode[204]; int Weight; PH *T = new PH(); scanf( "%d", &n ); while(n--) { scanf( "%s%d", &PWord,&Weight ); insert( PWord, Weight, T ); } scanf( "%d", &m ); cout<<"Scenario #"<<d<<':'<<endl; d++; while( m-- ) { p.ch = ' '; p.word = ""; p.weight = 100000; p.NOW = T; Q.push( p ); scanf( "%s", &PCode); search( PCode, T); while( !Q.empty() ) Q.pop(); printf("/n"); } printf("/n"); } }