UVA - 321 The New Villa

15 篇文章 0 订阅

题目大意:别墅有 r 个房间,d 扇门, s 个开关,判断是否能从编号 1 的房间走到编号 r 的房间,若能打印步骤。两个房间之间有门的才可移动,在移动时注意不能进入没有亮灯的房间。
解题思路:二进制表示房间状态,bfs 查找递归输出。

#include<iostream> 
#include<cstdio>
#include<cmath>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
int r, d, s;
int cnt = 0;
int vis[15][2000];
int pre[15][2000];
struct node {
    int step, now, state;
};
queue<node> q;
int door[15][15], light[15][15];
node now, nt;
void bfs() {
    int n, sta, t;
    while (!q.empty() && !vis[r][1]) {
        now = q.front(); q.pop();
        n = now.now;
        sta = now.state * 100 + n;
        nt.step = now.step + 1;
        for (int i = 1; i <= r; i++) {
            if (!light[n][i] || i == n) continue;
            t = now.state ^ (1 << (r-i));
            if (vis[n][t]) continue;
            vis[n][t] = nt.step;
            pre[n][t] = sta;
            nt.state = t;
            nt.now = n;
            q.push(nt);
        }
        for (int i = 1; i <= r; i++) {
            if (!door[n][i]) continue;
            if (!((1<<(r-i)) & now.state) || vis[i][now.state]) continue;
            vis[i][now.state] = nt.step;
            pre[i][now.state] = sta;
            nt.state = now.state;
            nt.now = i;
            q.push(nt);
        }
    }
}
void output(int n, int sta) {
    int ln, ls, t = pre[n][sta];
    if (!t) return;
    ln = t % 100;
    ls = t / 100;
    output(ln, ls);
    if(ln != n)printf("- Move to room %d.\n", n);  
    else {
        int t=ls^sta, i, flag;
        for(i = 0; i < r&&!(t&1); i++, t>>=1);  
        flag = ls&(1<<i);  
        printf("- Switch %s light in room %d.\n",flag?"off":"on",r-i);
    }  
}
int main() {
    while (scanf("%d%d%d", &r, &d, &s) != EOF && r+d+s) {
        memset(door, 0, sizeof(door));
        memset(light, 0, sizeof(light));
        memset(vis, 0, sizeof(vis));

        int a, b;
        for (int i = 0; i < d; i++) {
            scanf("%d%d", &a, &b);
            door[a][b] = door[b][a] = 1;
        }
        for (int i = 0; i < s; i++) {
            scanf("%d%d", &a, &b);
            light[a][b] = 1;
        }

        while (!q.empty()) q.pop();
        int i = 1 << (r - 1);
        vis[1][i] = 1;
        pre[1][i] = 0;
        now.state = i;
        now.now = 1;
        now.step = 1;
        q.push(now);

        printf("Villa #%d\n", ++cnt);
        bfs();
        if(vis[r][1]) {
            printf("The problem can be solved in %d steps:\n",vis[r][1]-1);
            output(r,1);
        }
        else printf("The problem cannot be solved.\n");  
        printf("\n");
    }
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值