[AHOI2014/JSOI2014]支线剧情
嘟嘟嘟
这是一道上下界费用流的模板题。
源点就是1,汇点没有,所以我们把每一个点都连向汇点,因为可以在任意一个点退出游戏。
上下界费用流的建图方法和上下界网络流的建图方法一样。都是建立附加源汇。只不过每条边多了个费用。
有费用的边就是他自己的费用,其他的(比如补偿用的边)的费用全是0。然后我们跑费用流,答案就是费用流的答案加下界流量乘以对应的费用。
上下界费用流的特点是满足流量限制下的最小(最大)费用。
而不是向普通费用流一样必须满流。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 305;
const int maxe = 1e7 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n, s, t, S, T;
int d[maxn], sum = 0;
struct Edge
{
int nxt, from, to, cap, cos;
}e[maxe];
int head[maxn], ecnt = -1;
In void addEdge(int x, int y, int w, int c)
{
e[++ecnt] = (Edge){head[x], x, y, w, c};
head[x] = ecnt;
e[++ecnt] = (Edge){head[y], y, x, 0, -c};
head[y] = ecnt;
}
bool in[maxn];
int dis[maxn], pre[maxn], flow[maxn];
In bool spfa()
{
Mem(dis, 0x3f), Mem(in, 0);
dis[S] = 0, flow[S] = INF;
queue<int> q; q.push(S);
while(!q.empty())
{
int now = q.front(); q.pop(); in[now] = 0;
for(int i = head[now], v; ~i; i = e[i].nxt)
{
if(dis[v = e[i].to] > dis[now] + e[i].cos && e[i].cap > 0)
{
dis[v] = dis[now] + e[i].cos;
pre[v] = i;
flow[v] = min(flow[now], e[i].cap);
if(!in[v]) q.push(v), in[v] = 1;
}
}
}
return dis[T] ^ INF;
}
int minCost = 0;
In void update()
{
int x = T;
while(x ^ S)
{
int i = pre[x];
e[i].cap -= flow[T];
e[i ^ 1].cap += flow[T];
x = e[i].from;
}
minCost += flow[T] * dis[T];
}
In int MCMF()
{
minCost = 0;
while(spfa()) update();
return minCost;
}
In void add(int x, int y, int Min, int Max, int c)
{
sum += Min * c;
d[x] += Min, d[y] -= Min;
addEdge(x, y, Max - Min, c);
}
In void build()
{
for(int i = 0; i <= t; ++i)
if(d[i] >= 0) addEdge(i, T, d[i], 0);
else addEdge(S, i, -d[i], 0);
addEdge(t, s, INF, 0);
}
int main()
{
Mem(head, -1);
n = read(); s = 1, t = n + 1;
S = t + 1, T = t + 2;
for(int i = 1; i <= n; ++i)
{
add(i, t, 0, INF, 0);
int m = read();
for(int j = 1; j <= m; ++j)
{
int x = read(), c = read();
add(i, x, 1, INF, c);
}
}
build();
write(sum + MCMF()), enter;
return 0;
}