[BZOJ2502]清理雪道(有上下界的网络流)

题目描述

传送门

题解

有上下界的网络流问题,新技能get

代码

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

const int max_n=105;
const int max_N=max_n+5;
const int max_m=max_n*max_n;
const int max_e=max_m*2;
const int INF=1e9;

int n,m,x,s,t,ss,tt,maxflow;
int d[max_n];
int tot,point[max_N],next[max_e],v[max_e],remain[max_e];
int deep[max_N],cur[max_N];
queue <int> q;

inline void addedge(int x,int y,int cap){
    ++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=cap;
    ++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=0;
}

inline bool bfs(int s,int t){
    for (int i=1;i<=n+4;++i) deep[i]=INF+1;
    deep[s]=0;
    for (int i=1;i<=n+4;++i) cur[i]=point[i];
    while (!q.empty()) q.pop();
    q.push(s);

    while (!q.empty()){
        int now=q.front(); q.pop();
        for (int i=point[now];i!=-1;i=next[i])
          if (deep[v[i]]>INF&&remain[i]){
            deep[v[i]]=deep[now]+1;
            q.push(v[i]);
          }
    }
    return deep[t]<INF;
}
inline int dfs(int now,int t,int limit){
    if (now==t||!limit) return limit;
    int flow=0,f;
    for (int i=cur[now];i!=-1;i=next[i]){
        cur[now]=i;
        if (deep[v[i]]==deep[now]+1&&(f=dfs(v[i],t,min(remain[i],limit)))){
            flow+=f;
            limit-=f;
            remain[i]-=f;
            remain[i^1]+=f;
            if (!limit) break;
        }
    }
    return flow;
}
inline void dinic(int s,int t){
    maxflow=0;
    while (bfs(s,t))
      maxflow+=dfs(s,t,INF);
}

int main(){
    tot=-1;
    memset(point,-1,sizeof(point));
    memset(next,-1,sizeof(next));

    scanf("%d",&n);
    s=n+1; t=s+1; ss=t+1; tt=ss+1;
    for (int i=1;i<=n;++i){
        scanf("%d",&m);
        for (int j=1;j<=m;++j)
          scanf("%d",&x),addedge(i,x,INF),d[i]--,d[x]++;
    }
    for (int i=1;i<=n;++i){
        if (d[i]>0) addedge(ss,i,d[i]);
        if (d[i]<0) addedge(i,tt,-d[i]);
        addedge(s,i,INF); addedge(i,t,INF);
    }
    dinic(ss,tt);
    addedge(t,s,INF);
    dinic(ss,tt);
    printf("%d\n",maxflow);
}

你可能感兴趣的:(网络流,bzoj)