# SGU 176 Flow construction 网络流 有上下界限制最小流

314人阅读 评论(0)

1.构建附加网络

2.求 ss 到 tt 的最大流

3.加入 t 到 s 容量为 INF 的边

4.再对 ss 到 tt 求一次最大流

5.若 ss 和 tt 满流，则 t 到 s 的流量即为最小流

6.若 5 不满足，则无可行流

#include<iostream>
#include<queue>
#include<cstdlib>
#include<vector>
#include<cstring>
#include<cstdio>
using namespace std;
const int INF = 0x7ffffff;
const int MAXN = 205;
const int MAXM = MAXN * MAXN;
int n, m, s, t, cnt;
bool vis[MAXN];
int d[MAXN], cur[MAXN], que[MAXN];
struct edge_{
int from, to, cap, flow, next;
}edge[MAXM];

void init(){
memset(edge, -1, sizeof(edge));
memset(deg, 0, sizeof(deg));
memset(dl, 0, sizeof(dl));
cnt = 0;
}

void add(int from, int to, int cap){
edge[cnt].from = from, edge[cnt].to = to;
edge[cnt].cap = cap, edge[cnt].next = head[from];
edge[cnt].flow = 0;
edge[cnt].from = to, edge[cnt].to = from;
edge[cnt].cap = 0, edge[cnt].next = head[to];
edge[cnt].flow = 0;
}

bool bfs(){
memset(vis, false, sizeof(vis));
memset(d, 0, sizeof(d));
d[s] = 0, vis[s] = 1, que[0] = s;
int tail = 0, front = 1;
while(tail < front){
int x = que[tail++];
for(int now = head[x]; ~now; now = edge[now].next){
edge_ &e = edge[now];
if(!vis[e.to] && e.cap > e.flow){
vis[e.to] = 1;
d[e.to] = d[x] + 1;
que[front++] = e.to;
}
}
}
return vis[t];
}

int dfs(int x, int a){
if(x == t || a == 0)
return a;
int flow = 0, f;
for(int &now = cur[x]; ~now; now = edge[now].next){
edge_ &e = edge[now];
if(d[x] + 1 == d[e.to] && (f = dfs(e.to, min(a, e.cap - e.flow))) > 0){
e.flow +=f;
edge[now ^ 1].flow -= f;
flow += f;
a -= f;
if(a == 0)
break;
}
}
return flow;
}

int maxFlow(int _s, int _t, int _n){
s = _s, t = _t, n = _n;
int flow = 0;
while(bfs()){
for(int i = 1; i <= n; i++)
flow += dfs(s, INF);
}
return flow;
}

int main(){
int n, m, s, t, l, r, ok, c;
while(~scanf("%d%d", &n, &m)){
init();
int ss = n + 1, tt = n + 2, sumf = 0, sum = 0;
for(int i = 1; i <= m; ++i){
scanf("%d%d%d%d", &s, &t, &c, &ok);
cap[i] = c;
if(t == n)
sumf += c;
if(ok){
deg[s] -= c, deg[t] += c, dl[i] = c;
}
else
}
for(int i = 1; i <= n; ++i){
if(deg[i] > 0)
add(ss, i, deg[i]), sum += deg[i];
else if(deg[i] < 0)
}
int ans = 0;
ans = maxFlow(ss, tt, n + 2);
ans += maxFlow(ss, tt, n + 2);
if(ans != sum){
printf("Impossible\n");
}
else{
printf("%d\n", edge[cnt - 2].flow);
for(int i = 0; i < m; ++i)
printf(i == 0 ? "%d" : " %d", edge[i * 2].flow + dl[i + 1]);
printf("\n");
}
}
return 0;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：29418次
• 积分：920
• 等级：
• 排名：千里之外
• 原创：65篇
• 转载：2篇
• 译文：0篇
• 评论：4条
阅读排行
评论排行
最新评论