http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1103
题目大意:
给出一副无向完全图,且每个点也有和自己的边。每条边有一种颜色,给出起始时三个棋子的状态。每次按照规则移动一个棋子,问最少多少步可以把所有棋子移动到同一个位置去。
移动的规则:The following constraint is imposed on this: the piece may only be moved along arrows of the same colour as the arrow between the two opponents' pieces. 假设移动棋子为A,另外两个棋子为BC,由于图的形状,BC之间必有一条弧,A沿着移动的弧必须与弧BC同色。
解题思路:
建立一个访问标记数组,然后从起始p1,p2,p3状态进行bfs.
解题心得:
不要老想着哈希,这才50*50*50。
Segmentation Fault了很多次,最后推倒了才过的,也不知道究竟是推倒了什么才解决的。
以后queue定义在生命周期恰好的地方比较好,定义在外面的话还要手工pop。
对付多空格和换行的时候可以用cin>>t_char来解决,或者用scanf("%s", str); str[0]这样。
源代码:
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
#define maxn 55
typedef struct node{
int x, y, z, k;
}node;
bool init(node &start, int &n, bool v[][maxn][maxn], char a[][maxn] )
{
char tmp;
scanf("%d", &n);
if (n==0) return false;
scanf("%d%d%d", &start.x, &start.y, &start.z);
start.x--; start.y--; start.z--;
start.k=0;
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
cin>>a[i][j]; //新学猥琐方法
memset(v, 0, sizeof(bool)*maxn*maxn*maxn);
return true;
}
int bfs(node start, int n, bool v[][maxn][maxn], char a[][maxn])
{
int x, y, z;
queue<node> q;
node now, next;
if (start.x==start.y && start.y==start.z) return 0;
v[start.x][start.y][start.z]=1;
q.push(start);
while (!q.empty())
{
now=q.front();
q.pop();
x=now.x; y=now.y; z=now.z; now.k++;
//move x
next=now;
for (int i=0; i<n; i++)
if (a[x][i]==a[y][z] && !v[i][y][z])
{
if (i==y && y==z) return next.k;
next.x=i;
q.push(next);
v[i][y][z]=1;
}
//move y
next=now;
for (int i=0; i<n; i++)
if (a[y][i]==a[x][z] && !v[x][i][z])
{
if (x==i && i==z) return next.k;
next.y=i;
q.push(next);
v[x][i][z]=1;
}
//move z
next=now;
for (int i=0; i<n; i++)
if (a[z][i]==a[x][y] && !v[x][y][i])
{
if (x==y && y==i) return next.k;
next.z=i;
q.push(next);
v[x][y][i]=1;
}
}
return -1;
}
int main()
{
int n, t;
bool v[maxn][maxn][maxn];
char a[maxn][maxn];
node start;
while (init(start, n, v, a))
{
if ((t=bfs(start, n, v, a))==-1) printf("impossible\n");
else printf("%d\n", t);
}
return 0;
}