Poj2688cleaningrobot
这道题让我们求一个地图上的各个点之间的最短路径说白了旅行商问题。
那么我们先用一个裸的BFS求出各个点之间的最短距离,然后我们再枚举各个点的全排列即可
这道题的细节很多,详见注释
上代码~
1 #include<stdio.h> 2 #include<algorithm> 3 #include<queue> 4 using namespace std; 5 int d[15][15];int w;int h; 6 char map[25][25];bool vis[25][25]; 7 int dx[4]={1,-1,0,0};int dy[4]={0,0,-1,1}; 8 int res; 9 struct data 10 { 11 int x;int y;int step; 12 }n[15],now;int cnt; 13 inline int s(int x,int y)//强制转换点坐标为点号 14 { 15 for(int i=0;i<=cnt;i++) 16 if(n[i].x==x&&n[i].y==y) 17 return i; 18 return 0; 19 } 20 queue <data> q; 21 int c[15]; 22 void clear()//因为每一个点都要bfs所以搜一次清空一次 23 { 24 while(!q.empty()) 25 { 26 q.pop(); 27 } 28 for(int i=0;i<h;i++) 29 for(int j=0;j<w;j++) 30 vis[i][j]=false; 31 return; 32 } 33 int main() 34 { 35 while(1) 36 { 37 res=0x3f3f3f3f;cnt=0;//多组询问的时候记得赋变量初值 38 scanf("%d%d",&w,&h); 39 if(w==0&&h==0)break; 40 for(int i=0;i<h;i++) 41 { 42 scanf("%s",map[i]); 43 for(int j=0;j<w;j++) 44 { 45 if(map[i][j]=='*') 46 { 47 n[++cnt].x=i;n[cnt].y=j; 48 } 49 else if(map[i][j]=='o') 50 { 51 n[0].x=i;n[0].y=j; 52 } 53 } 54 } 55 for(int i=0;i<=cnt;i++)//记得清空邻接矩阵 56 { 57 for(int j=0;j<=cnt;j++) 58 { 59 d[i][j]=0; 60 } 61 } 62 for(int i=0;i<=cnt;i++)//裸的bfs 63 { 64 q.push(n[i]); 65 //printf("STARTFROM%d\n",i); 66 vis[n[i].x][n[i].y]=true; 67 int rep=cnt; 68 while(!q.empty()) 69 { 70 now=q.front();q.pop(); 71 int x=now.x;int y=now.y; 72 //printf("nowis(%d,%d)\n",x,y); 73 for(int k=0;k<4;k++) 74 { 75 if(x+dx[k]<0||x+dx[k]>=h||y+dy[k]<0||y+dy[k]>=w|| 76 vis[x+dx[k]][y+dy[k]]||map[x+dx[k]][y+dy[k]]=='x')//地图中是小写的x 77 continue; 78 if(map[x+dx[k]][y+dy[k]]=='*'||map[x+dx[k]][y+dy[k]]=='o') 79 { 80 int t=s(x+dx[k],y+dy[k]); 81 //printf("REACH%d,DISis%d\n",t,now.step+1); 82 d[i][t]=now.step+1; 83 d[t][i]=now.step+1; 84 rep--; 85 if(rep==0)goto nxt; 86 } 87 vis[x+dx[k]][y+dy[k]]=true; 88 data p;p.x=x+dx[k];p.y=y+dy[k];p.step=now.step+1; 89 q.push(p); 90 } 91 } 92 nxt:; 93 clear(); 94 } 95 for(int i=0;i<=cnt;i++) 96 { 97 c[i]=i; 98 //printf("node%dis(%d,%d)\n",i,n[i].x,n[i].y); 99 } 100 int rep; 101 /*for(int i=0;i<=cnt;i++) 102 { 103 for(int j=0;j<=cnt;j++) 104 { 105 printf("%-3d",d[i][j]); 106 } 107 printf("\n"); 108 }*/ 109 do 110 { 111 rep=0; 112 for(int i=0;i<cnt;i++) 113 { 114 //printf("%-2d",c[i]); 115 if(d[c[i]][c[i+1]]==0) 116 { 117 printf("-1\n");goto ed; 118 } 119 rep+=d[c[i]][c[i+1]]; 120 } 121 //printf("%-2d",c[cnt]); 122 //printf("%-5d",rep); 123 if(res>rep)res=rep; 124 //printf("\n"); 125 }while(next_permutation(c+1,c+cnt+1));//枚举全排列 126 printf("%d\n",res); 127 ed:; 128 } 129 return 0;//拜拜程序~ 130 }
posted on 2017-10-17 16:34 SHADOWICENCXIX 阅读(210) 评论(0) 编辑 收藏 举报