题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1044
思路:看网上大牛们的做法都是bfs+dfs,弱菜表示不会啊,然后觉得bfs也应该不会超时吧,就搞了一把,orz...890ms险过。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 #define MAXN 52 7 struct Node{ 8 int x,y,time; 9 int value,key; 10 }; 11 char map[MAXN][MAXN]; 12 bool mark[MAXN][MAXN][1212]; 13 int value[MAXN]; 14 int n,m,t,l,ans; 15 int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; 16 Node st,ed; 17 bool flag; 18 19 void bfs(){ 20 memset(mark,false,sizeof(mark)); 21 queue<Node>Q; 22 Node p,q; 23 Q.push(st); 24 while(!Q.empty()){ 25 p=Q.front(); 26 Q.pop(); 27 if(p.time>t)continue; 28 if(p.x==ed.x&&p.y==ed.y&&p.time<=t){ 29 ans=max(ans,p.value); 30 flag=true; 31 } 32 for(int i=0;i<=4;i++){ 33 q.x=p.x+dir[i][0]; 34 q.y=p.y+dir[i][1]; 35 q.key=p.key; 36 q.value=p.value; 37 q.time=p.time; 38 if(q.x<1||q.x>n||q.y<1||q.y>m||map[q.x][q.y]=='*')continue; 39 if(map[q.x][q.y]>='A'&&map[q.x][q.y]<='J'){ 40 int x=map[q.x][q.y]-'A'; 41 int y=value[x]; 42 if(q.key&(1<<x)){ 43 q.time+=1; 44 if(!mark[q.x][q.y][q.key]){ mark[q.x][q.y][q.key]=true;Q.push(q); } 45 }else { 46 q.key+=(1<<x); 47 q.value+=value[x+1]; 48 q.time+=1; 49 if(!mark[q.x][q.y][q.key]){ mark[q.x][q.y][q.key]=true;Q.push(q); } 50 } 51 }else if(!mark[q.x][q.y][q.key]){ 52 mark[q.x][q.y][q.key]=true; 53 q.time+=1; 54 Q.push(q); 55 } 56 } 57 } 58 } 59 60 61 int main(){ 62 int _case,x=1; 63 scanf("%d",&_case); 64 while(_case--){ 65 if(x>1)puts(""); 66 scanf("%d%d%d%d",&m,&n,&t,&l); 67 for(int i=1;i<=l;i++)scanf("%d",&value[i]); 68 for(int i=1;i<=n;i++){ 69 scanf("%s",map[i]+1); 70 for(int j=1;j<=m;j++){ 71 if(map[i][j]=='@'){ st.x=i,st.y=j,st.time=0,st.key=0,st.value=0; } 72 else if(map[i][j]=='<'){ ed.x=i,ed.y=j,ed.time=t,ed.key=0,ed.value=0; } 73 } 74 } 75 ans=0,flag=false; 76 bfs(); 77 printf("Case %d:\n",x++); 78 if(flag){ 79 printf("The best score is %d.\n",ans); 80 }else 81 puts("Impossible"); 82 } 83 return 0; 84 }