#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <set> #include <vector> #include <map> #include <queue> #include <set> #include <algorithm> #include <limits> using namespace std; typedef long long LL; const int MAXN=1e+5; const int MAXM=1e+6; const int INF = numeric_limits<int>::max(); const LL LL_INF= numeric_limits<LL>::max(); struct Edge { int to,ci,cost,next; Edge(){} Edge(int _to,int _ci,int _cost,int _next):to(_to),ci(_ci),cost(_cost),next(_next){} }e[MAXM]; int head[MAXN],tot; int q[MAXM]; int dis[MAXN],pre[MAXN],rec[MAXN],vis[MAXN]; inline void init(){ memset(head,-1,sizeof(head)); tot=0; } inline void AddEdge1(int u,int v,int ci,int cost){ e[tot]=Edge(v,ci,cost,head[u]); head[u]=tot++; e[tot]=Edge(u,0,-cost,head[v]); head[v]=tot++; } inline bool spfa(int S,int T,LL &cost,LL &flow){ int i,h=0,t=0; for(i=0;i<MAXN;i++){ dis[i]=INF; vis[i]=false; } q[h]=S; dis[S]=0; vis[S]=true; while(h<=t){ int u=q[h++]; vis[u]=false; for(i=head[u];~i;i=e[i].next){ int v=e[i].to; if(e[i].ci>0&&dis[v]>dis[u]+e[i].cost){ dis[v]=dis[u]+e[i].cost; pre[v]=u; rec[v]=i; if(!vis[v]){ vis[v]=1; q[++t]=v; } } } } if(dis[T]==INF)return false; int minn=INF; for(i=T;i!=S;i=pre[i]){ if(e[rec[i]].ci<minn) minn=e[rec[i]].ci; } for(i=T;i!=S;i=pre[i]){ e[rec[i]].ci-=minn; e[rec[i]^1].ci+=minn; } cost+=dis[T]*minn; flow+=minn; return true; } inline void mincostmaxflow(int S,int T,LL &cost,LL &flow){ while(spfa(S,T,cost,flow)); } int mapp[210][210]; int main() { int n; while(~scanf("%d",&n)){ if(!n)break; init(); memset(mapp,-1,sizeof(mapp)); for(int i=1;i<=n;i++){ int x,y; while(~scanf("%d",&x)&&x){ scanf("%d",&y); while(y<0); if(mapp[i][x]==-1)mapp[i][x]=y; else mapp[i][x]=min(mapp[i][x],y); } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(mapp[i][j]!=-1)AddEdge1(i<<1,j<<1|1,1,mapp[i][j]); } } int st=0,et=1; for(int i=1;i<=n;i++){ AddEdge1(st,i<<1,1,0); AddEdge1(i<<1|1,et,1,0); } LL flow=0,cost=0; mincostmaxflow(st,et,cost,flow); if(flow!=(LL)n)puts("N"); else printf("%lld\n",cost); } return 0; }
|