这个题是二分图最佳完美匹配,第一次用最小费用流做~
代码:
#include<cstdio> #include<cstring> #include<iostream> #include<queue> using namespace std; const int inf=1<<29; const int maxn=210; const int maxm=2*maxn*maxn; int e,st,des,n,m,head[maxn],nxt[maxm],cost[maxm],pnt[maxm],flow[maxm],dist[maxn],pre[maxn]; bool vis[maxn]; queue<int> q; void AddEdge(int u,int v,int f,int c) { pnt[e]=v;nxt[e]=head[u];flow[e]=f;cost[e]=c;head[u]=e++; pnt[e]=u;nxt[e]=head[v];flow[e]=0;cost[e]=-c;head[v]=e++; } bool Spfa(int st,int des) { for(int i=st;i<=des;i++) { dist[i]=inf; pre[i]=-1; } dist[st]=0; q.push(st); while(!q.empty()) { int u=q.front(); vis[u]=0; q.pop(); for(int i=head[u];i!=-1;i=nxt[i]) { if(flow[i]&&dist[pnt[i]]>dist[u]+cost[i]) { dist[pnt[i]]=dist[u]+cost[i]; pre[pnt[i]]=i; if(!vis[pnt[i]]) { vis[pnt[i]]=1; q.push(pnt[i]); } } } } return dist[des]!=inf; } void maxflow() { int ans=0,minicost=0; while(Spfa(st,des)) { int mini=inf; for(int i=pre[des];i!=-1;i=pre[pnt[i^1]]) mini=min(mini,flow[i]); for(int i=pre[des];i!=-1;i=pre[pnt[i^1]]) { flow[i]-=mini; flow[i^1]+=mini; } ans+=mini; minicost+=mini*dist[des]; } if(ans!=n) { printf("N\n"); return; } printf("%d\n",minicost); } int main() { while(scanf("%d",&n)&&n) { e=st=0; des=2*n+1; memset(head,-1,sizeof(head)); for(int i=1;i<=n;i++) { int v,c; while(scanf("%d",&v)&&v) { scanf("%d",&c); AddEdge(i,n+v,1,c); } } for(int i=1;i<=n;i++) { AddEdge(st,i,1,0); AddEdge(n+i,des,1,0); } maxflow(); } return 0; }