标签:des blog http io ar os sp for div
Description
Input
Output
Sample Input
Sample Output
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; typedef pair<int,int >P; #define EMPTY(x,j) (~((x)&(1<<(j)))) const int inf=0x7ffffff; int n,m; char maz[201][201];int ind[201][201],k; int px[15],py[15]; int dis[128000][2]; bool vis[128000][2]; bool inmaze(int x,int y){ return x>=0&&x<n&&y>=0&&y<m; } bool ok(int x,int y,int x2,int y2){ if(inmaze(x,y)&&maz[x][y]==‘#‘)return false; if(inmaze(x2,y2)&&maz[x2][y2]==‘#‘)return false; return true; } const int dx[4][2]={{0,1},{1,0},{-1,0},{0,-1}}; const int dy[4][2]={{1,0},{0,-1},{0,1},{-1,0}}; int main(){ while(scanf("%d%d",&n,&m)==2&&m){ k=0; memset(ind,0,sizeof(ind)); for(int i=0;i<n;i++)scanf("%s",maz[i]); for(int i=0;i<n;i++)for(int j=0;j<m;j++){ if(maz[i][j]==‘.‘){ px[k]=i; py[k]=j; ind[i][j]=k++; } } if(k==0){puts("0");continue;} fill(dis[0],dis[0]+(1<<(k+1)),inf); fill(vis[0],vis[0]+(1<<(k+1)),0); vis[0][0]=vis[0][1]=true; dis[0][0]=0; queue<P> que; que.push(P(0,false)); while(!que.empty()){ int sta=que.front().first;int fl=que.front().second;que.pop(); if(sta==(1<<k)-1)break; vis[sta][fl]=false; for(int i=0;i<k;i++){ { int sx=px[i],sy=py[i]; if(ok(sx-1,sy,sx,sy+1)){ int tsta=sta|(1<<i); if(inmaze(sx-1,sy))tsta|=(1<<ind[sx-1][sy]); if(inmaze(sx,sy+1))tsta|=(1<<ind[sx][sy+1]); if(dis[tsta][fl]>dis[sta][fl]+1){ dis[tsta][fl]=dis[sta][fl]+1; if(!vis[tsta][fl]){ vis[tsta][fl]=true; que.push(P(tsta,fl)); } } } if(fl)continue; for(int j=0;j<4;j++){ int tx[2]={sx+dx[j][0],sx+dx[j][1]},ty[2]={sy+dy[j][0],sy+dy[j][1]}; if(ok(tx[0],ty[0],tx[1],ty[1])){ int tsta=sta|(1<<i); if(inmaze(tx[0],ty[0]))tsta|=(1<<ind[tx[0]][ty[0]]); if(inmaze(tx[1],ty[1]))tsta|=(1<<ind[tx[1]][ty[1]]); if(dis[tsta][1]>dis[sta][0]+1){ dis[tsta][1]=dis[sta][0]+1; if(!vis[tsta][1]){ vis[tsta][1]=true; que.push(P(tsta,1)); } } } } } } } int ans=min(dis[(1<<k)-1][0],dis[(1<<k)-1][1]); printf("%d\n",ans==inf?-1:ans); } return 0; }
hdu 4770 13 杭州 现场 A - Lights Against Dudely 暴力 bfs
标签:des blog http io ar os sp for div
原文地址:http://www.cnblogs.com/xuesu/p/4103337.html