POJ1451T9

来源:互联网 发布:三菱plc编程指令详解 编辑:程序博客网 时间:2024/05/16 06:35
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <queue>


using namespace std;




struct  tire
{
   tire* next[26];
   int total;
   tire* pre;
   char letter;


   tire()
   {
       for( int i = 0 ; i< 26; i++)
       {
           next[i] = NULL;
           total = 0;
           letter = '\0';
           pre = NULL;
       }
   }
} ;






void insert( char str[],int n, tire *root)
{
    tire *p = root;
    int len = strlen(str);
    for( int i = 0; i< len; i++)
    {
        if(p->next[str[i]-'a'] == NULL)
         {
             p->next[str[i]-'a'] = new tire;
             p->next[str[i]-'a']->pre = p;
             p->next[str[i]-'a']->letter = str[i];
         }
        p = p->next[str[i] -'a'];
        p->total += n;
    }
}




void output(tire * point)
{
    if(point->pre->pre!= NULL)
     output(point->pre);
    printf("%c",point->letter);
}


char T9[10][5] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
void bfs(char *num,tire *root)
{
    queue<tire*> q;
    q.push(root);
    for(int i = 0;num[i]!= '1';i++)
    {
        int size = q.size(),max = 0;
        tire*now = NULL;


        while(size--)
        {
            tire *head = q.front();
            q.pop();


           for( int j =0; j<strlen(T9[num[i]-'0']); j++)
           {
               tire *temp = head->next[T9[num[i]-'0'][j]-'a'];
               if(temp != NULL)
               {
                   if(temp->total>max)
                   {
                       max = temp->total;
                       now = temp;
                   }
                   q.push(temp);
               }
           }
        }
        if(now == NULL)
         printf("MANUALLY");
        else
          output(now);
        printf("\n");
    }
printf("\n");
}




int main()
{
  int t;
  scanf("%d",&t);
  for( int i = 0 ; i<t; i++)
  {
      printf("Scenario #%d:\n",i+1);
      tire root;
      int w,m;
      for(scanf("%d",&w);w>0;w--)
      {
          char str[101];
          int p;
          scanf("%s%d",str,&p);
          insert(str,p,&root);
      }


      for(scanf("%d",&m);m>0;m--)
      {
          char num[101];
          scanf("%s",num);
          bfs(num,&root);
      }
      printf("\n");
  }




}
0 0