题意:十个房间让你走到第十个,条件是只有当房间是亮着的你才可以进去,每个房间都有相应的房间可以控制,我们用二进制来表示所有房间的亮灯情况,
一题hash的应用
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int Switch[12][12],stnum[12];
int vis[100005],door[12][12];
int r,d,s;
struct node
{
int room,step,status,pre; //pre表示前一个节点,用于打印节点
}path[100005];
bool insert(int s)
{
int h = path[s].status * 10 + path[s].room - 1;
if (vis[h])
return false;
vis[h] = 1;
return true;
}
int change(int rnum)
{
for (int i = 0; i < 15; i++) //找那个1的位置
if ((1<<i) == rnum)
return i + 1;
return 0;
}
void print(int s)
{
int u = path[s].pre;
if (s)
print(u); // 0 的状态是全零的,所以下面的全部成立
if (path[u].room != path[s].room)
printf("- Move to room %d.\n",path[s].room);
else if (path[u].status < path[s].status)
printf("- Switch on light in room %d.\n", change(path[s].status - path[u].status));
else if (path[u].status > path[s].status)
printf("- Switch off light in room %d.\n", change(path[u].status - path[s].status));
}
void bfs()
{
memset(vis,0,sizeof(vis));
int front = 0,rear = 1;
path[0].pre = 0,path[0].step = 0;
path[0].status = 1,path[0].room = 1;
insert(0);
while (front < rear)
{
int x = path[front].room;
if (x == r && path[front].status == (1<<(r-1)))
{
printf("The problem can be solved in %d steps:\n", path[front].step);
print(front);
return ;
}
for (int i = 1; i <= r; i++)
if (door[x][i] && (1<<(i-1)&path[front].status)) //i灯是开着的
{
path[rear].pre = front;
path[rear].room = i;
path[rear].step = path[front].step + 1;
path[rear].status = path[front].status;
if (insert(rear))
rear++;
}
for (int i = 0; i < stnum[x]; i++)
{
int y = Switch[x][i];
path[rear].pre = front;
path[rear].room = x;
if (1<<(y-1)&path[front].status)
path[rear].status = path[front].status - (1<<(y-1));
else path[rear].status = path[front].status + (1<<(y-1));
path[rear].step = path[front].step + 1;
if (1<<(x-1)&path[rear].status && insert(rear)) //只有不关掉现在的房间的灯
rear++;
}
++front;
}
printf("The problem cannot be solved.\n");
}
int main()
{
int x,y,t=1;
while (scanf("%d%d%d",&r,&d,&s) != EOF && r+d+s)
{
memset(stnum,0,sizeof(stnum));
memset(door,0,sizeof(door));
for (int i = 0; i < d; i++)
{
scanf("%d%d",&x,&y);
door[x][y] = door[y][x] = 1;
}
for (int i = 0; i < s; ++i)
{
scanf("%d%d",&x,&y);
Switch[x][stnum[x]++] = y;
}
printf("Villa #%d\n",t++);
bfs();
printf("\n");
}
return 0;
}
一题hash的应用