BZOJ 3876: [Ahoi2014]支线剧情 [上下界费用流]

3876: [Ahoi2014]支线剧情

题意:每次只能从1开始,每条边至少经过一次,有边权,求最小花费


裸上下界费用流...每条边下界为1就行了

注意要加上下界*边权

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define fir first
#define sec second
typedef long long ll;
const int N=1005, M=4e5+5, INF=1e9;
inline ll read(){
    char c=getchar();ll x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}

int n, m, s, t, tot, extra[N], x, val, ss, tt, sum; 
struct edge{int v, c, f, w, ne, lower;}e[M];
int cnt=1, h[N];
inline void ins(int u, int v, int c, int w=0, int lower=0) {
	e[++cnt] = (edge){v, c, 0, w, h[u], lower}; h[u]=cnt;
	e[++cnt] = (edge){u, 0, 0, -w, h[v], lower}; h[v]=cnt;
}
int q[N], head, tail, d[N], inq[N];
pair<int, int> pre[N];
inline void lop(int &x) {if(x==N) x=1;}
bool spfa(int s, int t) {
	memset(inq, 0, sizeof(inq));
	memset(d, 0x3f, sizeof(d));
	head=tail=1;
	q[tail++]=s; d[s]=0; inq[s]=1;
	pre[t].fir = -1;
	while(head!=tail) {
		int u=q[head++]; inq[u]=0; lop(head);
		for(int i=h[u];i;i=e[i].ne) {
			int v=e[i].v;
			if(e[i].c > e[i].f && d[v]>d[u]+e[i].w) {
				d[v]=d[u]+e[i].w;
				pre[v]=make_pair(u, i);
				if(!inq[v]) q[tail++]=v, inq[v]=1, lop(tail);
			}
		}
	}
	return pre[t].fir != -1;
}
int ek(int s, int t) {
	int flow=0, cost=0, x;
	while(spfa(s, t)) {
		int f=INF;
		for(int i=t; i!=s; i=pre[i].fir) x=pre[i].sec, f=min(f, e[x].c - e[x].f);
		flow+=f; cost+=d[t]*f;
		for(int i=t; i!=s; i=pre[i].fir) x=pre[i].sec, e[x].f+=f, e[x^1].f-=f;
	}
	return cost;
}

int main() {
	freopen("in","r",stdin);
	n=read(); s=0; t=n+1; 
	ins(s, 1, INF, 0, 0);
	int ans=0;
	for(int i=1; i<=n; i++) {
		int k=read();
		while(k--) x=read(), val=read(), ins(i, x, INF, val, 1), extra[i]--, extra[x]++, ans+=val;
		ins(i, t, INF, 0, 0);
	}
	ss=t+1, tt=t+2, sum=0; tot=tt;
	for(int i=s; i<=t; i++) {
		if(extra[i]>0) ins(ss, i, extra[i]);
		if(extra[i]<0) ins(i, tt, -extra[i]);
	}
	ins(t, s, INF);
	ans+=ek(ss, tt);
	printf("%d", ans);
}
posted @ 2017-03-28 21:47  Candy?  阅读(241)  评论(0编辑  收藏  举报