poj 1451(Trie)
生活随笔
收集整理的這篇文章主要介紹了
poj 1451(Trie)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:就是讓你模擬手機輸入單詞。具體就是給你一些單詞,以及該單詞被使用的頻數,這個頻數也是該單詞前綴的使用頻數,當然不同的單詞有可能有相同的前綴,那么這個相同的前綴的使用頻數就是這兩個單詞使用頻數之和,以此類推。然后再給你一些數字串,讓你針對該數字串的每一個前綴輸出它的最有可能對應的單詞(即頻數最大的字符串)。
解題思路:這道題目比我想象中的簡單,直接dfs去搜,因為每個鍵的字母個數不超過5,所以不會TLE。。。
#include<iostream> #include<cstdio> #include<cstring> using namespace std;struct node {struct node *next[26];int p;node(){p = 0;for(int i = 0; i < 26; i++)next[i] = NULL;} }; int n,pro; char s[100],keyboard[10][5]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; char ans[100],tmp[100];void add(char *str,int cnt,node *root) {node *t = root;for(int i = 0; str[i] != 0; i++){if(t->next[str[i]-'a'] == NULL){t->next[str[i]-'a'] = new node();}t = t->next[str[i]-'a'];t->p += cnt;} }void dfs(int x,int pos,node *r) {int num = s[pos] - '0';int len = strlen(keyboard[num]);for(int i = 0; i < len; i++){int t = keyboard[num][i] - 'a';if(r->next[t] == NULL) continue;else tmp[pos] = keyboard[num][i];if(pos == x){if(pro < r->next[t]->p){pro = r->next[t]->p;strcpy(ans,tmp);}}else dfs(x,pos+1,r->next[t]);} }int main() {int t,p,cas = 1;node *root;scanf("%d",&t);while(t--){root = new node();scanf("%d",&n);for(int i = 1; i <= n; i++){getchar();scanf("%s %d",s,&p);add(s,p,root);}printf("Scenario #%d:\n", cas++);scanf("%d",&n);for(int i = 1; i <= n; i++){getchar();scanf("%s",s);int len = strlen(s);for(int j = 0; j < len-1; j++){memset(tmp,0,sizeof(tmp));pro = 0;dfs(j,0,root);if(pro == 0)printf("MANUALLY\n\n");else printf("%s\n\n",ans);}}}return 0; }
總結
以上是生活随笔為你收集整理的poj 1451(Trie)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【发布】JEECG-P3 新主题后台风格
- 下一篇: 【升级包】jeecg_online 支持