给定一个\(01\)矩阵,其中你可以在 \(0\) 的位置放置攻击装置。
每一个攻击装置\((x,y)\)都可以按照“日”字攻击其周围的\(8\)个位置
\((x?1,y?2),(x?2,y?1),(x+1,y?2),(x+2,y?1),\)
\((x?1,y+2),(x?2,y+1),(x+1,y+2),(x+2,y+1)。\)
求在装置互不攻击的情况下,最多可以放置多少个装置。
最大权独立集模板题。
不能放置装置的点跳过即可。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 40100, M = 10 * N, inf = 1e8;
int n, S, T;
int h[N], e[M], ne[M], f[M], idx;
int cur[N], d[N];
char mp[210][210];
int dx[8] = {-1, -2, 1, 2, -1, -2, 1, 2};
int dy[8] = {-2, -1, -2, -1, 2, 1, 2, 1};
void add(int a, int b, int c)
{
e[idx] = b, f[idx] = c, ne[idx] = h[a], h[a] = idx ++;
e[idx] = a, f[idx] = 0, ne[idx] = h[b], h[b] = idx ++;
}
bool bfs()
{
memset(d, -1, sizeof(d));
queue<int> que;
que.push(S);
d[S] = 0, cur[S] = h[S];
while(que.size()) {
int t = que.front();
que.pop();
for(int i = h[t]; ~i; i = ne[i]) {
int ver = e[i];
if(d[ver] == -1 && f[i]) {
d[ver] = d[t] + 1;
cur[ver] = h[ver];
if(ver == T) return true;
que.push(ver);
}
}
}
return false;
}
int find(int u, int limit)
{
if(u == T) return limit;
int flow = 0;
for(int i = cur[u]; ~i && flow < limit; i = ne[i]) {
cur[u] = i;
int ver = e[i];
if(d[ver] == d[u] + 1 && f[i]) {
int t = find(ver, min(f[i], limit - flow));
if(!t) d[ver] = -1;
f[i] -= t, f[i ^ 1] += t, flow += t;
}
}
return flow;
}
int dinic()
{
int res = 0, flow;
while(bfs()) {
while(flow = find(S, inf)) {
res += flow;
}
}
return res;
}
int get(int x, int y)
{
return (x - 1) * n + y;
}
int main()
{
scanf("%d", &n);
memset(h, -1, sizeof(h));
S = 0, T = n * n + 1;
for(int i = 1; i <= n; i ++) scanf("%s", mp[i] + 1);
int tot = 0;
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
if(mp[i][j] == ‘1‘) continue;
int t = get(i, j);
if((i + j) % 2) add(S, t, 1);
else add(t, T, 1);
tot ++;
}
}
for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) {
if(mp[i][j] == ‘1‘) continue;
int t = get(i, j);
if((i + j) % 2) {
for(int k = 0; k < 8; k ++) {
int x = i + dx[k], y = j + dy[k];
if(x < 1 || x > n || y < 1 || y > n) continue;
if(mp[x][y] == ‘1‘) continue;
int p = get(x, y);
add(t, p, inf);
}
}
}
}
printf("%d\n", tot - dinic());
return 0;
}
原文:https://www.cnblogs.com/miraclepbc/p/14409002.html