题意
思路
这道题与(K)取方格数那道题如出一辙,唯一需要改变的就是不能通过的格点需要跳过。
这道题输出方案有点麻烦,这里有一个技巧就是只看上一个格子的出点与下一个格子的入点之间的边,如果这条边的反向边有流量那么可以走,并顺便将其减(1)
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 35 * 35 * 2 + 10, M = N * 4 + 10, inf = 1e8;
int n, m, S, T, K;
int h[N], e[M], f[M], ne[M], w[M], idx;
int pre[N], d[N], incf[N];
bool st[N];
int mp[40][40];
int dx[2] = {1, 0}, dy[4] = {0, 1};
void add(int a, int b, int c, int d)
{
e[idx] = b, f[idx] = c, w[idx] = d, ne[idx] = h[a], h[a] = idx ++;
e[idx] = a, f[idx] = 0, w[idx] = -d, ne[idx] = h[b], h[b] = idx ++;
}
bool spfa()
{
memset(d, 0x3f, sizeof(d));
memset(incf, 0, sizeof(incf));
queue<int> que;
que.push(S);
d[S] = 0, incf[S] = inf;
st[S] = true;
while(que.size()) {
int t = que.front();
que.pop();
st[t] = false;
for(int i = h[t]; ~i; i = ne[i]) {
int ver = e[i];
if(d[ver] > d[t] + w[i] && f[i]) {
d[ver] = d[t] + w[i];
pre[ver] = i;
incf[ver] = min(incf[t], f[i]);
if(!st[ver]) {
st[ver] = true;
que.push(ver);
}
}
}
}
return incf[T] > 0;
}
int EK()
{
int flow = 0;
while(spfa()) {
int t = incf[T];
flow += t;
for(int i = T; i != S; i = e[pre[i] ^ 1]) {
f[pre[i]] -= t;
f[pre[i] ^ 1] += t;
}
}
return flow;
}
int get(int x, int y, int k)
{
return (x - 1) * m + y + k * n * m;
}
void dfs(int p, int u)
{
if(u == n * m) return;
for(int i = h[u + n * m]; ~i; i = ne[i]) {
int ver = e[i];
if(i % 2) continue;
if(f[i ^ 1]) {
printf("%d ", p);
if(ver == u + 1) printf("1
");
else printf("0
");
f[i ^ 1] --;
return dfs(p, ver);
}
}
}
int main()
{
scanf("%d%d%d", &K, &m, &n);
memset(h, -1, sizeof(h));
S = 0, T = 2 * n * m + 1;
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= m; j ++) {
int x;
scanf("%d", &x);
mp[i][j] = x;
if(x == 2) {
add(get(i, j, 0), get(i, j, 1), 1, -1);
add(get(i, j, 0), get(i, j, 1), inf, 0);
}
else if(x == 0) add(get(i, j, 0), get(i, j, 1), inf, 0);
}
}
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= m; j ++) {
for(int k = 0; k < 2; k ++) {
int x = i + dx[k], y = j + dy[k];
if(mp[x][y] == 1) continue;
if(x < 1 || x > n || y < 1 || y > m) continue;
add(get(i, j, 1), get(x, y, 0), inf, 0);
}
}
}
add(S, get(1, 1, 0), K, 0);
add(get(n, m, 1), T, inf, 0);
int res = EK();
for(int i = 1; i <= res; i ++) dfs(i, 1);
return 0;
}