一道BFS的简单题.
题目大意: http://poj.org/problem?id=1130
我们抓到了一个外星人ET,现在他被关在一个房间,一共有很多个房间且相互连通,但是必须从第一个房间进入,问现在想放一个警卫在其中一个房间中,使得所有人无法到达外星人所在房间.如果有多个房间选择距离外星人所在房间最近的.
解题思路:
从ET所在房间开始BFS所有点,并且0点不能入队.对每BFS到的一个点,从图中删除,从0点开始BFS,看是否能到达ET所在的点.这样第一个能到达的点就是距离ET最近的控制点.
源代码:
#include <myhead>
const int N=10;
int n,m;
bool make[N],maket[N];
bool graph[N][N],grapht[N][N];
bool bfs() {
queue<int> q;
q.push(0);
make[0]=true;
while(!q.empty()) {
int t=q.front();
q.pop();
if(t==m) {
return false;
}
for(int i=1;i<n;++i) {
if(!make[i]&&graph[t][i]) {
make[i]=true;
q.push(i);
}
}
}
return true;
}
inline void work() {
queue<int> q;
q.push(m);
maket[m]=true;
while(!q.empty()) {
int t=q.front();
q.pop();
if(!t) continue;
for(int i=0;i<n;++i) {
if(!maket[i]&&grapht[t][i]) {
maket[i]=true;
q.push(i);
memset(make,false,sizeof(make));
make[i]=true;
if(bfs()) {
printf("Put guards in room %d.\n",i);
return ;
}
}
}
}
puts("Put guards in room 0.");
}
int main() {
while(~scanf("%d%d",&n,&m)) {
memset(maket,false,sizeof(maket));
memset(graph,false,sizeof(graph));
memset(grapht,false,sizeof(grapht));
int x,y;
while(~scanf("%d%d",&x,&y)) {
graph[x][y]=true;
grapht[y][x]=true;
}
work();
}
return 0;
}