loj 6007「网络流 24 题」方格取数

题目链接:https://loj.ac/problem/6007

题意:略。

思路:详解移步Seng Xian's Blog

#include<bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=30*30+5;
template<typename T>
inline T read(T&x){
    x=0;int _f=0;char ch=getchar();
    while(ch<'0'||ch>'9')_f|=(ch=='-'),ch=getchar();
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x=_f?-x:x;
}
struct Edge{
    int from,to,cap,flow;
    Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
int n,m;
int dir_x[]={0,1,0,-1};
int dir_y[]={1,0,-1,0};
struct Dinic{
    int n,m,s,t;
    vector<Edge>edges;
    vector<int>G[maxn];
    bool vis[maxn];
    int d[maxn];
    int cur[maxn];

    void init(int n){
        this->n=n;
        for (int i=0;i<n;i++) G[i].clear();
        edges.clear();
    }

    void AddEdge(int from,int to,int cap){
        edges.push_back(Edge(from,to,cap,0));
        edges.push_back(Edge(to,from,0,0));
        m=edges.size();
        G[from].push_back(m-2);
        G[to].push_back(m-1);
    }

    bool BFS(){
        memset(d,0,sizeof(d));
        memset(vis,0,sizeof(vis));
        queue<int>Q;
        Q.push(s);
        d[s]=0;
        vis[s]=1;
        while (!Q.empty()){
            int x=Q.front();Q.pop();
            for (int i=0;i<(int)G[x].size();i++){
                Edge& e=edges[G[x][i]];
                if (!vis[e.to] && e.cap>e.flow){
                    vis[e.to]=1;
                    d[e.to]=d[x]+1;
                    Q.push(e.to);
                }
            }
        }
        return vis[t];
    }

    int DFS(int x,int a){
        if (x==t || a==0) return a;
        int flow=0,f;
        for (int& i=cur[x];i<(int)G[x].size();i++){
            Edge& e=edges[G[x][i]];
            if (d[x]+1==d[e.to] && (f=DFS(e.to,min(a,e.cap-e.flow)))>0){
                e.flow+=f;
                edges[G[x][i]^1].flow-=f;
                flow+=f;
                a-=f;
                if (a==0) break;
            }
        }
        return flow;
    }

    int Maxflow(int s,int t){
        this->s=s;this->t=t;
        int flow=0;
        while (BFS()){
            memset(cur,0,sizeof(cur));
            flow+=DFS(s,INF);
        }
        return flow;
    }
}A;
bool ok(int x,int y){
    if (x>=1 && x<=m && y>=1 && y<=n) return true;
    return false;
}
int main(){
    read(m),read(n);
    A.init(m*n+2);
    int sum=0;
    for (int i=1;i<=m;i++){
        for (int j=1;j<=n;j++){
            int x;
            read(x);
            sum+=x;
            if ((i+j)%2==0){
                A.AddEdge(0,(i-1)*n+j,x);
                for (int k=0;k<4;k++){
                    int tx=i+dir_x[k];
                    int ty=j+dir_y[k];
                    if (ok(tx,ty)) A.AddEdge((i-1)*n+j,(tx-1)*n+ty,INF);
                }
            }
            else A.AddEdge((i-1)*n+j,m*n+1,x);
        }
    }
    printf("%d\n",sum-A.Maxflow(0,m*n+1));
    return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注