您的位置:首页 > 其它

动态字典树+DFS(HDU_1298)

2013-07-27 13:41 344 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: