bzoj1475 方格取数 最小割

版权声明:虽然是个蒟蒻但是转载还是要说一声的哟 https://blog.csdn.net/jpwang8/article/details/82701969

Description


在一个n*n的方格里,每个格子里都有一个正整数。从中取出若干数,使得任意两个取出的数所在格子没有公共边,且取出的数的总和尽量大。

第一行一个数n;(n<=30) 接下来n行每行n个数描述一个方阵

Solution


刷水题有益身心健康
黑板染色然后相邻的格子连INF跑最小割即可

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define fill(x,t) memset(x,t,sizeof(x))

typedef long long LL;
const LL INF=1000000000000000;
const int N=3005;
const int E=350005;

struct edge {int y; LL w; int next;} e[E];

int dis[N],ls[N],edCnt=1;

int read() {
    int x=0,v=1; char ch=getchar();
    for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
    for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
    return x*v;
}

void add_edge(int x,int y,LL w) {
    e[++edCnt]=(edge) {y,w,ls[x]}; ls[x]=edCnt;
    e[++edCnt]=(edge) {x,0,ls[y]}; ls[y]=edCnt;
}

LL find(int now,int ed,LL mn) {
    if (now==ed||!mn) return mn;
    LL ret=0;
    for (int i=ls[now];i;i=e[i].next) {
        if (e[i].w>0&&dis[now]+1==dis[e[i].y]) {
            LL d=find(e[i].y,ed,std:: min(mn-ret,e[i].w));
            e[i].w-=d; e[i^1].w+=d; ret+=d;
            if (mn==ret) break;
        }
    }
    return ret;
}

bool bfs(int st,int ed) {
    std:: queue <int> que;
    fill(dis,0);
    que.push(st); dis[st]=1;
    for (;!que.empty();) {
        int now=que.front(); que.pop();
        for (int i=ls[now];i;i=e[i].next) {
            if (e[i].w>0&&!dis[e[i].y]) {
                dis[e[i].y]=dis[now]+1;
                if (e[i].y==ed) return true;
                que.push(e[i].y);
            }
        }
    }
    return false;
}

LL dinic(int st,int ed) {
    LL ret=0;
    for (;bfs(st,ed);) ret+=find(st,ed,INF);
    return ret;
}

int main(void) {
    int n; scanf("%d",&n); LL ans=0;
    rep(i,1,n) rep(j,1,n) {
        LL x; scanf("%lld",&x); ans+=x;
        int now=(i-1)*n+j;
        if ((i+j)&1) {
            add_edge(0,now,x);
            if (i!=1) add_edge(now,now-n+n*n,INF);
            if (i!=n) add_edge(now,now+n+n*n,INF);
            if (j!=1) add_edge(now,now-1+n*n,INF);
            if (j!=n) add_edge(now,now+1+n*n,INF);
        } else add_edge(now+n*n,n*n*2+1,x);
    }
    printf("%lld\n", ans-dinic(0,n*n*2+1));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jpwang8/article/details/82701969