还要回去重学一遍上下界网络流。
最小费用最大流?
每条边(x,y)
源点S向y连一条容量为1,费用为边权的边
x向y连一条容量为inf,费用为边权的边
每个点x
x向1连一条容量为inf,费用为0的边
x向T连一条容量为x的出度,费用为0的边
就是把原来上下界网络流的建图方法改了一下
#include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> #include<iostream> #define maxn 310 #define maxm 30010 #define inf 1000000000 using namespace std; int head[maxn],to[maxm],c[maxm],len[maxm],p[maxm],next[maxm],fr[maxn],dis[maxn],q[maxn]; int a[maxn][110],tim[maxn][110]; bool vis[maxn]; int n,m,s,t,num,S,T,Ans; void addedge(int x,int y,int z,int w) { num++;p[num]=x;to[num]=y;c[num]=z;len[num]=w;next[num]=head[x];head[x]=num; num++;p[num]=y;to[num]=x;c[num]=0;len[num]=-w;next[num]=head[y];head[y]=num; } bool spfa() { for (int i=0;i<=T;i++) dis[i]=inf; int l=0,r=1; dis[S]=0;q[1]=S;vis[S]=1; while (l!=r) { l++;if (l==maxn) l=0; int x=q[l]; for (int p=head[x];p;p=next[p]) if (c[p] && dis[x]+len[p]<dis[to[p]]) { dis[to[p]]=dis[x]+len[p]; fr[to[p]]=p; if (!vis[to[p]]) { r++;if (r==maxn) r=0; q[r]=to[p];vis[to[p]]=1; } } vis[x]=0; } if (dis[T]==inf) return 0; else return 1; } void mcf() { int x=inf; for (int i=fr[T];i;i=fr[p[i]]) x=min(x,c[i]); for (int i=fr[T];i;i=fr[p[i]]) Ans+=x*len[i],c[i]-=x,c[i^1]+=x; } void costflow() { Ans=0; while (spfa()) mcf(); } int main() { scanf("%d",&n); num=1,S=n+1,T=n+2; for (int i=1;i<=n;i++) { int cnt,x,y; scanf("%d",&cnt); addedge(i,T,cnt,0); if (i!=1) addedge(i,1,inf,0); for (int j=1;j<=cnt;j++) { scanf("%d%d",&x,&y); addedge(S,x,1,y); addedge(i,x,inf,y); } } costflow(); printf("%d\n",Ans); return 0; }