很简单的模板题,不多说了
#include<iostream> #include<cstring> #include<cstdio> #define INF 0x3f3f3f3f #define MAXN 1000 #define ll long long using namespace std; struct Edge{ int u,v,cost; }edge[MAXN*40]; int pre[MAXN],id[MAXN],vis[MAXN]; ll in[MAXN]; ll zhuliu(int root,int n,int m){ ll res=0; while(1){ for(int i=0;i<n;i++) in[i]=INF; for(int i=0;i<m;i++) if(edge[i].u!=edge[i].v && edge[i].cost<in[edge[i].v]){ pre[edge[i].v]=edge[i].u; in[edge[i].v]=edge[i].cost; } for(int i=0;i<n;i++) if(i!=root && in[i]==INF) return -1; int tn=0; memset(id,-1,sizeof id); memset(vis,-1,sizeof vis); in[root]=0; for(int i=0;i<n;i++){ res+=in[i]; int v=i; while(v!=root && id[v]==-1 && vis[v]!=i){ vis[v]=i; v=pre[v]; } if(id[v]==-1 && v!=root){ for(int u=pre[v];u!=v;u=pre[u]) id[u]=tn; id[v]=tn++; } } if(tn==0) break; for(int i=0;i<n;i++) if(id[i]==-1) id[i]=tn++; for(int i=0;i<m;i++){ int v=edge[i].v; edge[i].u=id[edge[i].u]; edge[i].v=id[edge[i].v]; if(edge[i].u!=edge[i].v) edge[i].cost-=in[v]; } n=tn; root=id[root]; } return res; } int main(){ int N,n,m; cin >> N; for(int tt=1;tt<=N;tt++){ scanf("%d%d",&n,&m); for(int i=0;i<m;i++) scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].cost); int root=0; ll res=zhuliu(root,n,m); if(res==-1) printf("Case #%d: Possums!\n",tt); else printf("Case #%d: %d\n",tt,res); } return 0; }