using namespace std; int t,n; const int base=10005; struct Edge{ int from,to,cap,flow,cost; Edge(int from,int to,int cap,int flow,int cost):from(from),to(to),cap(cap),flow(flow),cost(cost){} }; struct MCMF{ int n,m,s,t; vector<Edge>edges; vector<int>G[maxn]; int inq[maxn],d[maxn],p[maxn],a[maxn]; void init(int n){ this->n=n; for(int i=0;i<n;i++) G[i].clear(); edges.clear(); } void AddEdge(int from,int to,int cap,int cost){ edges.push_back(Edge(from,to,cap,0,cost)); edges.push_back(Edge(to,from,0,0,-cost)); m=edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool BellmanFord(int s,int t,int& flow,int& cost){ for(int i=0;i<n;i++) d[i]=inf; memset(inq,0,sizeof(inq)); d[s]=0,inq[s]=1,p[s]=0,a[s]=inf; queue<int>Q; Q.push(s); while(!Q.empty()){ int u=Q.front(); Q.pop(); inq[u]=0; for(int i=0;i<(int)G[u].size();i++){ Edge& e=edges[G[u][i]]; if(e.cap>e.flow && d[e.to]>d[u]+e.cost){ d[e.to]=d[u]+e.cost; p[e.to]=G[u][i]; a[e.to]=min(a[u],e.cap-e.flow); if(!inq[e.to]){ Q.push(e.to); inq[e.to]=1; } } } } if(d[t]==inf) return false; flow+=a[t]; cost+=d[t]*a[t]; int u=t; while(u!=s){ edges[p[u]].flow+=a[t]; edges[p[u]^1].flow-=a[t]; u=edges[p[u]].from; } return true; } void Mincost(int s,int t){ int flow=0,cost=0; while(BellmanFord(s,t,flow,cost)); if(flow==3) printf("%d\n",cost); else printf("-1\n"); } }g; char s1[15],s2[15]; map<string,int>mp; int w,id; int main(){ freopen("input.txt","r",stdin); scanf("%d",&t); while(t--){ scanf("%d",&n); mp.clear(); g.init(maxn); id=0; int S=0,T=20010; for(int i=1;i<=n;i++){ scanf("%s%s%d",s1,s2,&w); if(!mp.count(s1)){ mp[s1]=++id; if(strcmp(s1,"Hongqiao")==0) g.AddEdge(mp[s1],mp[s1]+base,2,0); else if(strcmp(s1,"Qingdao")==0) g.AddEdge(mp[s1],mp[s1]+base,2,0); else g.AddEdge(mp[s1],mp[s1]+base,1,0); } if(!mp.count(s2)){ mp[s2]=++id; if(strcmp(s2,"Hongqiao")==0) g.AddEdge(mp[s2],mp[s2]+base,2,0); else if(strcmp(s2,"Qingdao")==0) g.AddEdge(mp[s2],mp[s2]+base,2,0); else g.AddEdge(mp[s2],mp[s2]+base,1,0); } g.AddEdge(mp[s1]+base,mp[s2],inf,w); g.AddEdge(mp[s2]+base,mp[s1],inf,w); } g.AddEdge(S,mp["Qingdao"],inf,0); g.AddEdge(S,mp["Xian"],inf,0); g.AddEdge(mp["Hongqiao"]+base,T,inf,0); g.AddEdge(mp["Pudong"]+base,T,inf,0); g.Mincost(S,T); } return 0; }
|