网络流初探
例题B题解
从源点向每个猪圈连边,每个人向汇点连边。然后对于每个人所能打开的猪圈,如果在此之前没有被其他人连过,就让这个猪圈连向这个人,否则让这个人连向之前那个人。
例题B代码
#include<bits/stdc++.h>
using namespace std;
inline int read(){
int x = 0, f = 1;char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-') f = -1;ch = getchar();}
while(ch >= '0' && ch <= '9'){x = (x << 1) + (x << 3) + (ch ^ 48);ch = getchar();}
return x * f;
}
const int maxn = 2e3 + 10, maxm = 5e5 + 10, INF = 0x3f3f3f3f;
int n, m;
int head[maxn], tot = 1;
struct edge{
int to, nexte, cap, flow;
edge(int to = 0,int ne = 0,int ca = 0,int fl = 0):to(to),nexte(ne),cap(ca),flow(fl){}
}e[maxm * 2];
void add(int u,int v,int cap){e[++tot] = edge(v,head[u],cap);head[u] = tot;}
void addd(int u,int v,int cap){add(u,v,cap);add(v, u, 0);}
int dep[maxn], cur[maxn];
int dfs(int u,int flow,int T){
// printf("%lld\n",u);
if(u == T)return flow;
int rest = 0, tmp = 0;
for(int i = cur[u];i && flow;i = e[i].nexte){
cur[u] = i; int v = e[i].to;
if(e[i].cap - e[i].flow > 0 && (dep[v] == dep[u] + 1)){
tmp = dfs(v,min(flow,e[i].cap - e[i].flow),T);
if(tmp == 0)dep[v] = INF;
e[i].flow += tmp; e[i ^ 1].flow -= tmp;
flow -= tmp;rest += tmp;
if(!flow)return rest;
}
}
return rest;
}
bool bfs(int S,int T){
queue<int> que;
for(int i = 1;i <= T;i++){dep[i] = INF;cur[i] = 0;}
que.push(S);dep[S] = 1; cur[S] = head[S];
while(!que.empty()){
int u = que.front(); que.pop();
for(int i = head[u];i;i = e[i].nexte){
int v = e[i].to;
if(e[i].cap - e[i].flow > 0 && dep[v] == INF){
que.push(v);
cur[v] = head[v];
dep[v] = dep[u] + 1;
if(v == T)return 1;
}
}
}
return 0;
}
int Dinic(int S,int T){
int mxflow = 0;
while(bfs(S,T)){mxflow += dfs(S,INF,T);}
return mxflow;
}
int match[maxn];
signed main(){
m = read(); n = read();int S = n + m + 1, T = n + m + 2;
for(int i = 1;i <= m;i++)addd(S,i,read());
for(int i = 1;i <= n;i++){
for(int j = read();j;j--){
int x = read();
if(!match[x])addd(x,i + m,INF);
else addd(match[x] + m,i + m,INF);
match[x] = i;
}
addd(i + m,T,read());
}
printf("%d\n",Dinic(S,T));
return 0;
}
标签:tmp,ch,return,int,flow,dep,初探,导航,金牌
From: https://www.cnblogs.com/Call-me-Eric/p/17894317.html