欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

洛谷P2774 方格取数问题(最小割)

程序员文章站 2022-10-17 10:17:05
题意 $n \times m$的矩阵,不能取相邻的元素,问最大能取多少 Sol 首先补集转化一下:最大权值 = sum - 使图不连通的最小权值 进行黑白染色 从S向黑点连权值为点权的边 从白点向T连权值为点券的边 黑点向白点连权值为INF的边 这样就转化成了最小割问题,跑Dinic即可 ......

题意

$n \times m$的矩阵,不能取相邻的元素,问最大能取多少

Sol

首先补集转化一下:最大权值 = sum - 使图不连通的最小权值

进行黑白染色

从S向黑点连权值为点权的边

从白点向T连权值为点券的边

黑点向白点连权值为INF的边

这样就转化成了最小割问题,跑Dinic即可

/*
首先补集转化一下:最大权值 = sum - 使图不连通的最小权值
进行黑白染色
从S向黑点连权值为点权的边
从白点向T连权值为点券的边
黑点向白点连权值为INF的边
跑Dinic
*/
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int MAXN = 1e5 + 10, INF = 1e9 + 10;
inline int read() {
    char c = getchar();
    int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = 1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N, M, a[101][101], black[101][101], S, T = 100001;
struct Edge {
    int u, v, f, nxt;
} E[MAXN];
int head[MAXN], cur[MAXN], num = 0;
inline void add_edge(int x, int y, int z) {
    E[num] = (Edge) {x, y, z, head[x]};
    head[x] = num++;    
}
inline void AddEdge(int x, int y, int z) {
    add_edge(x, y, z);
    add_edge(y, x, 0);
}
int trans(int x, int y) {
    return (x - 1) * M + y;
}
int xx[5] = {0, -1, +1, 0, 0};
int yy[5] = {0, 0, 0, -1, +1};
int deep[MAXN];
inline int BFS() {
    queue<int> q; q.push(S);
    memset(deep, 0, sizeof(deep));
    deep[S] = 1;
    while(!q.empty()) {
        int p = q.front(); q.pop();
        for(int i = head[p]; i != -1; i = E[i].nxt) {
            int to = E[i].v;
            if(!deep[to] && E[i].f) 
                deep[to] = deep[p] + 1, q.push(to);
        }
    }
    return deep[T];
}
int DFS(int x, int flow) {
    if(x == T) return flow;
    int ansflow = 0;
    for(int &i = cur[x]; i != -1; i = E[i].nxt) {
        int to = E[i].v;
        if(E[i].f && deep[to] == deep[x] + 1) {
            int nowflow = DFS(to, min(flow, E[i].f));
            E[i].f -= nowflow; E[i ^ 1].f += nowflow;
            flow -= nowflow; ansflow += nowflow;
            if(flow <= 0) break;
        }
    }
    return ansflow;
}
int Dinic() {
    int ans = 0;
    while(BFS()) {
        memcpy(cur, head, sizeof(head));
        ans += DFS(S, INF);
    }
    return ans;
}
int main() {
    memset(head, -1, sizeof(head));
    N = read();
    M = read();
    int sum = 0;
    for(int i = 1; i <= N; i++)
        for(int j = 1; j <= M; j++) {
            a[i][j] = read(); sum += a[i][j];
            if((i + j) % 2 == 0) {
                AddEdge(S, trans(i, j), a[i][j]);    
                for(int k = 1; k <= 4; k++) {
                    int wx = i + xx[k], wy = j + yy[k];
                    if(wx >= 1 && wx <= N && wy >= 1 && wy <= M)
                        AddEdge(trans(i, j), trans(wx, wy), INF);
                }
            }
            else AddEdge(trans(i, j), T, a[i][j]);
        }
    printf("%d", sum - Dinic());
    return 0;
}
/*
3 3
1 000 00-
1 00- 0-+
2 0-- -++

*/