动态字典树+DFS(HDU_1298)
#include <stdio.h> #include <string.h> #define MU 26 #define WLEN (100 + 2) struct node{ int pr; node *child[MU]; node() { pr = 0; memset(child,NULL,sizeof(child)); } }; char findStr[WLEN],temp[WLEN]; char findMap[][5] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; int findPr; void clear(node *root) { for(int i=0;i<MU;i++) { if(root->child[i] != NULL) clear(root->child[i]); } delete root; } void insert(node *root, char *str, int pr) { node *p = root; int len = strlen(str); for(int i=0; i<len; i++) { int k = str[i] - 'a'; if(p->child[k] == NULL) { p->child[k] = new node; } p->child[k]->pr += pr; p = p->child[k]; } } void dfs(node *root, char *str, int cur, int n) // end n-1 { if(cur == n) { if(root->pr > findPr) { findPr = root->pr; memcpy(findStr,temp,sizeof(findStr)); findStr[cur] = '\0'; } return ; } int curI = str[cur] - '0'; int len = strlen(findMap[curI]); for(int j=0; j<len; j++) { int k = findMap[curI][j] - 'a'; if(root->child[k] == NULL) continue; temp[cur] = findMap[curI][j]; dfs(root->child[k], str, cur+1, n); } } void cutFind(node *root, char *str) { int len = strlen(str); for(int i=1; i<len; i++) //len-1 '1'; { findPr = -1; dfs(root,str,0,i); if(findPr > 0) printf("%s\n",findStr); else printf("MANUALLY\n"); } printf("\n"); } int main(int argc, char* argv[]) { #ifdef __MYLOCAL freopen("in.txt","r",stdin); #endif int __case,t,w,m,i,p; char id[WLEN]; node *root; scanf("%d",&t); for(__case=1; __case<=t; __case++) { root = new node; scanf("%d",&w); for(i=0; i<w; i++) { scanf("%s %d",id,&p); insert(root,id,p); } printf("Scenario #%d:\n",__case); scanf("%d",&m); for(i=0; i<m; i++) { scanf("%s",id); cutFind(root,id); } printf("\n"); clear(root); } return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步