Step1 Problem:
给你 n 个点,m 条流量下界是 low ,上界是 inf 的单向边。+ 是源点,- 是汇点。
如果存在可行流,求源点到汇点的最小流。
数据范围:
0 <= n <= 50, 1 <= m <= 200, 1 <= low <= 100.
Step2 Ideas:
有源汇可行流的流量只是对应一组可行流,并不是最大流或者最小流。
S->T 跑一波最大流,先把不需要经过 t->s 的流量跑掉。
然后建立 t->s 流量为 inf 的边,
在跑 S->T 最大流,这时的最大流 = t->s 流的流量。
此时 t->s 流的流量就是在满足可行流下,至少需要的最小流。
Step3 Code:
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 600;
const int M = 100000;
struct node
{
int to, cap, next;
}Map[M];
int s, t, S, T;
int head[N], cnt, lsum[N];
int vis[N], cur[N];
bool bfs(int s, int e)
{
memset(vis, -1, sizeof(vis));
queue<int> q;
q.push(s);
vis[s] = 0;
while(!q.empty())
{
s = q.front(), q.pop();
for(int i = head[s]; ~i; i = Map[i].next)
{
int to = Map[i].to, cap = Map[i].cap;
if(cap && vis[to] == -1)
{
vis[to] = vis[s] + 1;
q.push(to);
}
}
}
if(vis[e] == -1) return 0;
else return 1;
}
int dfs(int s, int e, int f)
{
if(s == e) return f;
int ans = 0;
for(int &i = cur[s]; ~i; i = Map[i].next)
{
int to = Map[i].to, &cap = Map[i].cap;
if(vis[to] > vis[s] && cap)
{
int d = dfs(to, e, min(f, cap));
if(d)
{
cap -= d;
Map[i^1].cap += d;
f -= d;
ans += d;
if(!f) break;
}
}
}
if(ans) return ans;
vis[s] = -1;
return 0;
}
int dinic(int s, int e)
{
int ans = 0;
while(bfs(s, e))
{
memcpy(cur, head, sizeof(head));
ans += dfs(s, e, inf);
}
return ans;
}
int read()
{
char s1[10];
scanf("%s", s1);
if(s1[0] == '+') return s;
else if(s1[0] == '-') return t;
int sum;
sscanf(s1, "%d", &sum);
return sum;
}
void add(int u, int v, int cap)
{
Map[cnt] = (node){v, cap, head[u]};
head[u] = cnt++;
Map[cnt] = (node){u, 0, head[v]};
head[v] = cnt++;
}
int main()
{
int n, m;
while(~scanf("%d %d", &n, &m) && (n||m))
{
cnt = 0;
memset(head, -1, sizeof(head));
memset(lsum, 0, sizeof(lsum));
s = 0, t = n+1, S = n+2, T = n+3;
int u, v, w;
for(int i = 1; i <= m; i++)
{
u = read(), v = read(), w = read();
add(u, v, inf);
lsum[v] += w;
lsum[u] -= w;
}
int sum = 0;
for(int i = 0; i <= n+1; i++) {
if(lsum[i] > 0) {
sum += lsum[i];
add(S, i, lsum[i]);
}
if(lsum[i] < 0) add(i, T, -lsum[i]);
}
dinic(S, T);
add(t, s, inf);
dinic(S, T);
int flag = true;
for(int i = head[S]; ~i; i = Map[i].next)
{
if(Map[i].cap) {//超级源点得满流
flag = false;
break;
}
}
if(flag) {
for(int i = head[s]; ~i; i = Map[i].next)
{
if(Map[i].to == t) {
printf("%d\n", Map[i].cap);//输出 t->s 流过的流量
break;
}
}
}
else printf("impossible\n");//不满流
// int ans, sum1=0;
// sum1 += dinic(S, T);
// add(t, s, inf);
// ans = dinic(S, T);//ans = t->s 流过的流量
// sum1 += ans;
// if(sum == sum1)
// {
// printf("%d\n", ans);
// }
// else printf("impossible\n");
}
return 0;
}