初见安~这里是传送门:洛谷P4011 [网络流24题] 孤岛营救问题
题解
这个题是真的不知道用网络流该怎么写了……QvQ因为一眼就是一个分层bfs……
首先确定是bfs过后考虑,钥匙种类很少,可以状压表示当前手里的钥匙。因为拿到钥匙后涉及到返回,所以可以对每个拿到钥匙的状态进行分层标记vis。原理很好理解,同样是拿这些钥匙,我去一个走过的地方那肯定不如之前走的时候的时间优。
没了。【??!】真不是我懒啊,题太水了QAQ
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#define maxn 15
using namespace std;
typedef long long ll;
int read() {
int x = 0, f = 1, ch = getchar();
while(!isdigit(ch)) {if(ch == '-') f = -1; ch = getchar();}
while(isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar();
return x * f;
}
int n, m, p, k, s;//p kinds of keys and doors.
int gate[maxn][maxn][maxn][maxn], key[maxn][maxn];
bool wall[maxn][maxn][maxn][maxn], vis[1 << maxn][maxn][maxn];//vis分层
struct node {int x, y, state, dis;};
queue<node> q;
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
bool in(int x, int y) {return 0 < x && x <= n && 0 < y && y <= m;}
int bfs() {//bfs基操
q.push({1, 1, 0, 0});
while(q.size()) {
node now = q.front(); q.pop();
if(now.x == n && now.y == m) return now.dis;
for(int i = 0; i < 4; i++) {
register int tx = now.x + dir[i][0], ty = now.y + dir[i][1];
if(in(tx, ty) && !wall[now.x][now.y][tx][ty] && !vis[now.state][tx][ty]) {
if((gate[now.x][now.y][tx][ty] && (now.state & gate[now.x][now.y][tx][ty])) || !gate[now.x][now.y][tx][ty])
vis[now.state][tx][ty] = true, q.push({tx, ty, now.state | key[tx][ty], now.dis + 1});
}
}
}
return -1;
}
signed main() {
n = read(), m = read(), p = read(), k = read();
for(int i = 1; i <= k; i++) {//gate是大门,wall是墙。比较暴力的存图
register int x1 = read(), y1 = read(), x2 = read(), y2 = read(), G = read();
if(!G) wall[x1][y1][x2][y2] = true, wall[x2][y2][x1][y1] = true;
else gate[x1][y1][x2][y2] = (1 << G), gate[x2][y2][x1][y1] = (1 << G);
}
s = read(); register int x, y, G;
for(int i = 1; i <= s; i++) x = read(), y = read(), G = read(), key[x][y] += (1 << G);
printf("%d\n", bfs());
return 0;
}
迎评:)
——End——