【Uva 1601】The Morning after Halloween
:
给你一张平面图;
最多可能有3只鬼;
给出这几只鬼的初始位置;
然后,这几只鬼有各自的终点;
每秒钟,这几只鬼能同时移动到相邻的4个格子中的一个
任意两只鬼不能交换位置
两只鬼不能走到同一个位置
问你都走到终点最短的时间.
因为图很小;
所以把二维的图;
转换成n*m个点;
然后建立点与点之间的关系;
(每个点和相邻的4个非墙的点连边)
转化成一维的点;
即因为是小图,所以转换成点,线图
这样处理起来比较简单,不用每次都找附近的4个点;
处理的时候,给每个点增加一个出度,出度指向自身,表示待在原地不动
转成点之后;
用dis[x][y][z],表示第一个人到了点x,第二个人到了点y,第三个人走到了点z的最小花费;
如果鬼的个数没达到3个;
就增加一个虚拟的节点;
那个节点增加一个出度自己;
即只会原地走;
每个节点的编号不会超过)
因为有说每个2*2就会有一个墙;
所以可以把3个人的位置
用x<<16+y<<8+z 来表示
(两个左箭头表示位左移)
想通过状态获取信息的时候
a=(sta>>16)&255,b = (sta>>8)&255,c = sta&255
枚举每个人鬼走到了哪里就好
三重for循环,然后判断交换位置的情况
0
直接找相邻的点比较麻烦;
转换成点、边图的形式,处理起来比较方便.
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 16;
const int M = 256;
const int MAXM = 192;
const int dx[6] = {0,1,-1,0,0,0};
const int dy[6] = {0,0,0,1,-1,0};
int w,h,n;
char s[N+5][N+5];
int g[M+5][M+5],st[4],en[4],cnt,mp[M+10][2],idx[M+5][M+5];
int f[MAXM+5][MAXM+5][MAXM+5];
queue <int> dl;
int get_num(int a,int b,int c){
return (a<<16) + (b<<8) + c;
}
void solve(){
memset(f,-1,sizeof f);
f[st[1]][st[2]][st[3]] = 0;
int s = get_num(st[1],st[2],st[3]);
dl.push(s);
while (!dl.empty()){
int x = dl.front();
dl.pop();
int a = (x>>16)&255,b = (x>>8)&255,c = x&255;
for (int i = 1;i <= g[a][0];i++){
int ta = g[a][i];
for (int j = 1;j <= g[b][0];j++){
int tb = g[b][j];
if (ta==tb) continue;
if (tb==a && ta == b) continue;
for (int k = 1;k <= g[c][0];k++){
int tc = g[c][k];
if (tc==ta || tc == tb) continue;
if (tc==a && ta==c) continue;
if (tc==b && tb==c) continue;
int y = get_num(ta,tb,tc);
if (f[ta][tb][tc]==-1){
f[ta][tb][tc] = f[a][b][c] + 1;
dl.push(y);
}
}
}
}
}
printf("%d
",f[en[1]][en[2]][en[3]]);
}
int main(){
//freopen("F:\rush.txt","r",stdin);
while (~scanf("%d%d%d",&w,&h,&n)){
if (w==0 && h==0 && n==0) break;
getchar();
cnt = 0;
for (int i = 1;i <= h;i++)
gets(s[i]+1);
for (int i = 1;i <= h;i++){
for (int j = 1;j <= w;j++)
if (s[i][j]!='#'){
cnt++;
idx[i][j] = cnt;
mp[cnt][0] = i,mp[cnt][1] = j;
if (s[i][j]>='a' && s[i][j] <='z'){
st[s[i][j]-'a'+1] = cnt;
}
if (s[i][j]>='A' && s[i][j] <='C'){
en[s[i][j]-'A'+1] = cnt;
}
}
}
for (int i = 1;i <= cnt;i++){
int x = mp[i][0],y = mp[i][1];
g[i][0] = 0;
for (int j = 1;j <= 5;j++){
int tx = x + dx[j],ty = y + dy[j];
if (tx < 1 || tx > h || ty <1 || ty > w) continue;
if (s[tx][ty]=='#') continue;
g[i][0]++;
g[i][g[i][0]] = idx[tx][ty];
}
}
if (n <= 2){
cnt++;
g[cnt][0] = 1;
g[cnt][1] = cnt;
st[3] = cnt,en[3] = cnt;
}
if (n <= 1){
cnt++;
g[cnt][0] = 1;
g[cnt][1] = cnt;
st[2] = cnt,en[2] = cnt;
}
solve();
}
return 0;
}