算法1
有源汇上下界最小费用可行流
时间复杂度
C++ 代码
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 310, M = (5000 + N * 4) * 2, INF = 0x3f3f3f3f;
int n;
int h[N], e[M], ne[M], f[M], w[M], idx;
int din[N], dout[N];
int S, T;
int incf[N], d[N], q[N], pre[N], hh, tt;
bool st[N];
void add(int a, int b, int c, int d)
{
e[idx] = b, ne[idx] = h[a], f[idx] = c, w[idx] = d, h[a] = idx ++;
e[idx] = a, ne[idx] = h[b], f[idx] = 0, w[idx] = -d, h[b] = idx ++;
}
bool spfa()
{
memset(d, 0x3f, sizeof d);
memset(incf, 0, sizeof incf);
incf[S] = INF, st[S] = true;
q[0] = S, d[S] = 0, hh = 0, tt = 1;
while(hh != tt)
{
int t = q[hh ++ ];
st[t] = false;
if(hh == N) hh = 0;
for(int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if(f[i] && d[j] > d[t] + w[i])
{
d[j] = d[t] + w[i];
incf[j] = min(incf[t], f[i]);
pre[j] = i;
if(!st[j])
{
q[tt ++ ] = j;
if(tt == N) tt = 0;
st[j] = true;
}
}
}
}
return incf[T] > 0;
}
int EK()
{
int flow = 0, cost = 0;
while(spfa())
{
int t = incf[T];
flow += t;
cost += t * d[T];
for(int i = T; i != S; i = e[pre[i] ^ 1])
{
f[pre[i]] -= t;
f[pre[i] ^ 1] += t;
}
}
return cost;
}
int main()
{
scanf("%d", &n);
memset(h, -1, sizeof h);
S = 0, T = n + 2;
int tot = 0;
for(int i = 1; i <= n; ++ i)
{
int k;
scanf("%d", &k);
if(!k)
{
add(i, n + 1, INF, 0);
continue;
}
for(int j = 0; j < k; ++ j)
{
int v, c;
scanf("%d %d", &v, &c);
add(i, v, INF, c);
din[v] ++, dout[i] ++;
tot += c;
}
}
add(n + 1, 1, INF, 0);
for(int i = 2; i <= n; ++ i) add(i, n + 1, INF, 0);
for(int i = 1; i <= n + 1; ++ i)
{
if(din[i] > dout[i])
add(S, i, din[i] - dout[i], 0);
else if(din[i] < dout[i])
add(i, T, dout[i] - din[i], 0);
}
printf("%d", EK() + tot);
return 0;
}