题目:http://acm.hust.edu.cn/vjudge/problem/11025
题意:有n个点用m个导管连接,物质可以在导管中流动,从起点1流到终点n。每次输入u v z c描述一个导管,u v代表导管连接u v两点且从u流向v,c有0 1两种值,为0时导管的流量不大于z,为1时导管内的流量必须为z,即上下界都为z。问满足要求的最小流量
思路:有源汇有上下界的最小流问题。
/*du[i]表示i节点的入流之和与出流之和的差。
*增设附加源点sups和附加汇点supt,连边(sups,du[i](为正)),(-du[i](为负),supt)。
*对附加源点和附加汇点做一次最大流
*从汇点tt到源点ss连一条容量为无穷大的边
*再次对附加源点和附加汇点做一次最大流
*当且仅当所有附加弧满载时有可行流,最后答案为经过边tt -> ss的流量
*/
#include
#include
#include
#include
using namespace std;
const int N = 110;
const int INF = 0x3f3f3f3f;
struct edge
{
int to, cap, next, id;
}g[N*N*2];
int cnt, nv, head[N], level[N], gap[N], cur[N], pre[N];
int du[N], dn[N*N];
void add_edge(int v, int u, int cap, int id = 0)
{
g[cnt].to = u, g[cnt].cap = cap, g[cnt].next = head[v], g[cnt].id = 0, head[v] = cnt++;
g[cnt].to = v, g[cnt].cap = 0, g[cnt].next = head[u], g[cnt].id = id, head[u] = cnt++;
}
int sap(int s, int t)
{
memset(level, 0, sizeof level);
memset(gap, 0, sizeof gap);
memcpy(cur, head, sizeof head);
gap[0] = nv;
int v = pre[s] = s, flow = 0, aug = INF;
while(level[s] < nv)
{
bool flag = false;
for(int &i = cur[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && level[v] == level[u] + 1)
{
flag = true;
pre[u] = v;
v = u;
aug = min(aug, g[i].cap);
if(v == t)
{
flow += aug;
while(v != s)
{
v = pre[v];
g[cur[v]].cap -= aug;
g[cur[v]^1].cap += aug;
}
aug = INF;
}
break;
}
}
if(flag) continue;
int minlevel = nv;
for(int i = head[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && minlevel > level[u])
minlevel = level[u], cur[v] = i;
}
if(--gap[level[v]] == 0) break;
level[v] = minlevel + 1;
gap[level[v]]++;
v = pre[v];
}
return flow;
}
int main()
{
int n, m, u, v, z, c;
while(~ scanf("%d%d", &n, &m))
{
cnt = 0;
memset(head, -1, sizeof head);
memset(du, 0, sizeof du);
memset(dn, 0, sizeof dn);
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d%d", &u, &v, &z, &c);
if(c == 1) du[v] += z, du[u] -= z, dn[i] = z;
else add_edge(u, v, z, i);
}
int ss = 1, tt = n, num = cnt;
int sups = 0, supt = n + 1;
for(int i = 1; i <= n; i++)
{
if(du[i] > 0) add_edge(sups, i, du[i]);
if(du[i] < 0) add_edge(i, supt, -du[i]);
}
nv = supt + 1;
sap(sups, supt);
add_edge(tt, ss, INF);
int tmp = cnt - 1;
sap(sups, supt);
bool flag = true;
for(int i = head[sups]; i != -1; i = g[i].next)
if(g[i].cap > 0)
{
flag = false; break;
}
if(!flag) puts("Impossible");
else
{
printf("%d\n", g[tmp].cap);
for(int i = 0; i < num; i++) dn[g[i].id] = g[i].cap;
for(int i = 1; i <= m; i++) printf("%d%c", dn[i], i == m ? '\n' : ' ');
}
}
return 0;
}