如题,话说这些网络流的本质本蒟蒻都不是很清楚(只会打板orzzz
#include
#include
#include
#include
#include
#define inf 0x7fffffff
using namespace std;
const int N=2e6+10;
int n,m,cnt,S,T,SS,TT;
int head[355],nxt[N],to[N],w[N],v[N],in[N];
int cost,mxflow,sum,tot=1,vis[N],dis[N],pt[N];
deque<int>Q;
inline int rd()
{
char ch=getchar();int x=0,f=1;
while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
while(isdigit(ch)){x=x*10+(ch^48);ch=getchar();}
return x*f;
}
inline void lk(int u,int k,int cap,int ty)
{to[++tot]=k;nxt[tot]=head[u];head[u]=tot;w[tot]=cap;v[tot]=ty;}
inline bool bfs(int s,int t)
{
int i,j,x;
for(i=1;i<=TT;++i) vis[i]=0,dis[i]=inf,pt[i]=0;
vis[s]=1;dis[s]=0;Q.push_back(s);
while(!Q.empty()){
x=Q.front();Q.pop_front();
for(i=head[x];i;i=nxt[i]){
j=to[i];
if(w[i] && dis[j]>(dis[x]+v[i])){
dis[j]=dis[x]+v[i];pt[j]=i;
if(!vis[j]){
if(!Q.empty() && dis[j]else Q.push_back(j);vis[j]=1;
}
}
}vis[x]=0;
}
return pt[t];
}
inline int imin(int x,int y){return x>y?y:x;}
inline void xflow(int s,int t)
{
int i,j,low;
while(bfs(s,t)){
for(low=inf,i=t;i;i=to[pt[i]^1]) low=imin(low,w[pt[i]]);
cost+=low*dis[t];
for(i=t;i;i=to[pt[i]^1]) w[pt[i]]-=low,w[pt[i]^1]+=low;
}
}
int main(){
int i,j,k,cc;
n=rd();
S=1;T=n+1;SS=0;TT=T+1;
for(i=1;i<=n;++i){
cnt=rd();in[i]-=cnt;lk(i,T,inf,0);lk(T,i,0,0);
while(cnt--)
{k=rd(),cc=rd();lk(i,k,inf,cc);lk(k,i,0,-cc);in[k]++;sum+=cc;}
}
for(i=1;i<=n;++i){
if(in[i]>0) lk(SS,i,in[i],0),lk(i,SS,0,0);
else if(in[i]<0) lk(i,TT,-in[i],0),lk(TT,i,0,0);
}lk(T,S,inf,0);lk(S,T,0,0);
xflow(SS,TT);
printf("%d\n",sum+cost);
}