题解:P4210 土地划分

· · 题解

思路

明显的最小割问题,用最大流算法解决。默认读者会最小割。

答案即为总价值减最小割。

总价值为所有 \mathit{VA}_i,\mathit{VB}_i,\mathit{EA}_i 及 \mathit{EB}_i 之和。

建图

此题重点在于建图废话。

对于以下两条规则:

直接连城市 1 向城市 i 的边,边权为 \mathit{VA}_i 和城市 i 向城市 1 的边,边权为 0 即可。

与上面同理。

但是还有三条规则:

于是我们借鉴一下 P1361 的做法。

首先建两个虚点,令两个城市为 u 和 v。

第一个虚点 p_1,连接城市 1 向 p_1 的边,边权为 \mathit{EA}_i。

再连接 p_1 向 u 和 v 的边,边权都为无穷大。

这两步相当于将 u 和 v 整合为一个点 p_1,p_1 向 u 和 v 的边的边权赋值为无穷大的意义是为了使得他俩尽可能被划分到一起。

第二个虚点 p_2 同理,用来连接 u 和 v 到城市 n。

对于以上操作,都要加与其反向的边权为 0 的边。

那对于扣除 \mathit{EC}_i 的得分呢?

这个其实十分简单,只需建连接 u 和 v 的双向边,边权为 \mathit{EC}_i 即可。

建图毕。

最小割

根据最大流最小割定理,最小割等于最大流。

直接将 P3376 的代码重写抄一遍即可。

注意到 n \le 10^4,m \le 4\times 10^4,EK 能过我直接吃,于是选择 Dinic。

经本人试验,加不加当前弧优化都能过。

为什么时间复杂度为 O(n^2m) 的跑这么快啊!

所以我们要相信 Dinic 神力。

代码

思路及具体做法皆在上文解释过,在代码中就不多加赘述。

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;//开大一点没坏处
int n,m,s,t,p,sum;
struct node{
    int to,next,w;
}e[2*maxn];
int head[maxn],tot=1;
void add(int u,int v,int w){
    e[++tot].to=v;
    e[tot].w=w;
    e[tot].next=head[u];
    head[u]=tot;
}
int dep[maxn],cur[maxn];
bool bfs(){
    queue<int> q;
    memset(dep,-1,sizeof(dep));
    q.push(s); dep[s]=0;
    while(!q.empty()){
        int u=q.front(); q.pop();
        for(int i=head[u];i;i=e[i].next){
            int v=e[i].to;
            if(dep[v]==-1&&e[i].w){
                dep[v]=dep[u]+1;
                q.push(v);
            }
        }
    }
    if(dep[t]==-1) return 0;
    return 1;
}
int dfs(int u,int flow){
    if(u==t) return flow;
    int used=flow;
    for(int i=cur[u];i;i=e[i].next){
        cur[u]=i;//当前弧优化
        int v=e[i].to;
        if(dep[v]==dep[u]+1&&e[i].w){
            int rlow=dfs(v,min(used,e[i].w));
            e[i].w-=rlow; e[i^1].w+=rlow;
            used-=rlow;
            if(used==0) break;
        }
    }
    return flow-used;
}
int dinic(){
    int ans=0;
    while(bfs()){
        memcpy(cur,head,sizeof(head));
        ans+=dfs(s,INT_MAX);
    }
    return ans;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin>>n>>m; s=1,t=n; p=n;
    for(int i=2;i<n;i++){
        int x;
        cin>>x; sum+=x;
        add(s,i,x); add(i,s,0);
    }
    for(int i=2;i<n;i++){
        int x;
        cin>>x; sum+=x;
        add(i,t,x); add(t,i,0);
    }
    for(int i=1;i<=m;i++){
        int u,v,ea,eb,ec;
        cin>>u>>v>>ea>>eb>>ec; sum+=ea+eb;
        add(u,v,ec); add(v,u,ec);
        int p1=n+i;
        add(s,p1,ea); add(p1,s,0);
        add(p1,u,INT_MAX); add(u,p1,0);
        add(p1,v,INT_MAX); add(v,p1,0);
        int p2=n+m+i;
        add(p2,t,eb); add(t,p2,0);
        add(u,p2,INT_MAX); add(p2,u,0);
        add(v,p2,INT_MAX); add(p2,v,0);
    }
    cout<<sum-dinic();
    return 0;
}