#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#define N 305
#define M N*N
#define INF 2e8
using namespace std;
int read()
{
int a=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){a=a*10+c-'0';c=getchar();}
return a*f;
}
struct edge{int from,to,c,v;};
vector<edge>e;
vector<int>G[N];
int n,S,T,d[N];
void add(int x,int y,int c,int v)
{
e.push_back((edge){x,y,c,v});
G[x].push_back(e.size()-1);
e.push_back((edge){y,x,0,-v});
G[y].push_back(e.size()-1);
}
int v[N],pre[N],du[N];
int spfa(int s,int t)
{
for(int i=1;i<=t;++i) d[i]=INF,v[i]=0;
queue<int>q;
q.push(s);
d[s]=0;v[s]=1;
while(!q.empty())
{
int x=q.front();q.pop();
for(int i=0;i<G[x].size();++i)
{
int y=G[x][i];
if(e[y].c&&d[e[y].to]>d[x]+e[y].v)
{
d[e[y].to]=d[x]+e[y].v;
pre[e[y].to]=y;
if(!v[e[y].to]) v[e[y].to]=1,q.push(e[y].to);
}
}
v[x]=0;
}
return d[t]!=INF;
}
int solve(int s,int t)
{
int res=0;
while(spfa(s,t))
{
int f=INF,to;
for(to=t;to!=s;to=e[pre[to]].from) f=min(f,e[pre[to]].c);
for(to=t;to!=s;to=e[pre[to]].from) e[pre[to]].c-=f,e[pre[to]^1].c+=f;
res+=d[t]*f;
}
return res;
}
int ans=0;
int main()
{
n=read();
for(int i=1,m,a,b;i<=n;++i)
{
m=read();
du[i]-=m;
while(m--)
{
a=read(),b=read();
add(i,a,INF,b);
++du[a];ans+=b;
}
if(i!=1) add(i,1,INF,0);
}
S=n+1,T=S+1;
for(int i=1;i<=n;++i)
{
if(du[i]>0) add(S,i,du[i],0);
if(du[i]<0) add(i,T,-du[i],0);
}
printf("%d\n",solve(S,T)+ans);
return 0;
}
有时间的话就补一篇学习笔记吧