Loading

代码-洛谷P4313 文理分科

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
#define x first
#define y second
#define bg begin()
#define ed end()
#define pb push_back
#define mp make_pair
#define sz(a) int((a).size())
#define R(i,n) for(int i(0);i<(n);++i)
#define L(i,n) for(int i((n)-1);~i;--i)
const int iinf=0x3f3f3f3f;
const ll linf=0x3f3f3f3f3f3f3f3f;

//Data
const int N=100;
int n,m;
vector<pair<int,int>> ne({{-1,0},{1,0},{0,1},{0,-1},{0,0}});

//Flows
const int fN=N*N*3+2;
int fn,s,t,e[fN];
vector<int> nex,to,fw;
void adde(int u,int v,int w){
    nex.pb(e[u]),to.pb(v),fw.pb(w),e[u]=sz(to)-1;
    nex.pb(e[v]),to.pb(u),fw.pb(0),e[v]=sz(to)-1;
}
int dep[fN],cur[fN];
bool bfs(){
    R(u,fn) dep[u]=-1,cur[u]=e[u];
    static queue<int> q;
    while(sz(q)) q.pop(); q.push(s),dep[s]=0;
    while(sz(q)){
        int u=q.front(); q.pop();
        for(int v=e[u];~v;v=nex[v])if(fw[v]&&!~dep[to[v]]){
            dep[to[v]]=dep[u]+1;
            if(to[v]==t) return true;
            q.push(to[v]);
        }
    }
    return false;
}
int dfs(int u,int r){
    if(u==t||!r) return r;
    int res=0,f;
    for(int &v=cur[u];~v;v=nex[v])
        if(fw[v]&&dep[to[v]]==dep[u]+1&&(f=dfs(to[v],min(r,fw[v])))>0)
            {fw[v]-=f,fw[v^1]+=f,r-=f,res+=f;if(!r) break;}
    return res;
}
int flow(){
    int res=0,f;
    while(bfs())while((f=dfs(s,iinf))) res+=f;
    return res;
}

//Main
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>n>>m,fn=(t=(s=n*m*3)+1)+1;
    R(u,fn) e[u]=-1; int x,sm=0;
    R(i,n)R(j,m) cin>>x,adde(s,i*m+j,x),sm+=x;
    R(i,n)R(j,m) cin>>x,adde(i*m+j,t,x),sm+=x;
    R(i,n)R(j,m) cin>>x,adde(s,i*m+j+n*m,x),sm+=x;
    R(i,n)R(j,m) cin>>x,adde(i*m+j+n*m*2,t,x),sm+=x;
    R(i,n)R(j,m)for(pair<int,int> d:ne){
        int x=i+d.x,y=j+d.y; if(x<0||x>=n||y<0||y>=m) continue;
        adde(i*m+j+n*m,x*m+y,iinf),adde(x*m+y,i*m+j+n*m*2,iinf);
    }
    cout<<sm-flow()<<'\n';
    return 0;
}
posted @ 2020-11-18 14:31  George1123  阅读(45)  评论(0编辑  收藏  举报