hdu1298字典树

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <string>
#include <string.h>
#include <map>
#include <vector>

const int nodeSize = 1000*100+8 ;
const int alphaSize = 26 ;

struct Trie{
    int root ;
    int totel ;
    int next[nodeSize][alphaSize] ;
    int cnt[nodeSize] ;

    int newNode(){
        memset(next[totel] , 0 , sizeof(next[totel])) ;
        cnt[totel] = 0 ;
        return totel++ ;
    }

    void clear(){
         totel = 0 ;
         root = newNode() ;
    }

    void add(char *s , int f){
         int now = root ;
         for(int i = 0 ; s[i] ; i++){
              int son = s[i] - 'a' ;
              if(! next[now][son]){
                    next[now][son] = newNode() ;
              }
              now = next[now][son] ;
              cnt[now] += f ;
         }
    }

};

Trie trie ;

char word[108] ;
char dir[10][8] = {"" , "" , "abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz"} ;

std::string res[108] ;
int cnt[108] ;

void dfs(int step , int now ,  std::string nowStr){
    // printf("%d %s\n" , step , nowStr.c_str()) ;
     if(step > 0){
           if(trie.cnt[now] > cnt[step]){
                cnt[step] = trie.cnt[now] ;
                res[step] = nowStr ;
           }
     }
     if(word[step] == '1') return ;

     int d = word[step] - '0' ;
     for(int i = 0 ; dir[d][i] ; i++){
          int son = dir[d][i] - 'a' ;
          if(! trie.next[now][son]) continue ;
          dfs(step+1 , trie.next[now][son] , nowStr + dir[d][i] ) ;
     }
}

int main(){

    int t , n , k ;
    scanf("%d" , &t) ;
    for(int cas = 1 ; cas <= t ; cas++){
        scanf("%d" , &n) ;
        trie.clear() ;
        for(int i = 0 ; i < n ; i++){
            scanf("%s%d" , word , &k) ;
            trie.add(word , k) ;
        }
        printf("Scenario #%d:\n" , cas) ;
        scanf("%d" , &n) ;
        for(int i = 0 ; i < n ; i++){
            scanf("%s" , word) ;
            int len = strlen(word) ;
            std::fill(res , res+len+1, "MANUALLY") ;
            memset(cnt , 0 , sizeof(cnt)) ;
            dfs(0 , trie.root ,  "") ;
            for(int i = 1 ; i < len ; i++)  printf("%s\n" , res[i].c_str()) ;
            puts("") ; 
        }
        puts("") ; 
    }
    return 0 ;
}

你可能感兴趣的:(hdu1298字典树)