最小树形图
#include<cstdio>
#include<cmath>
#define type int
using namespace std;
const int mm=44444;
const int mn=1111;
const int oo=1000000000;
type c[mm],in[mn],ans;
int s[mm],t[mm],id[mn],pre[mn],q[mn];
type Directed_MST(int root,int NV,int NE)
{
type ret=0;
int i,j,u,v,cnt,r;
while(1)
{
for(i=0;i<=NV;++i)in[i]=oo;
for(i=0;i<NE;++i)
if((u=s[i])!=(v=t[i])&&in[v]>c[i])
pre[v]=u,in[v]=c[i];
pre[root]=-1,in[root]=0;
for(i=1;i<=NV;++i)
if(in[i]==oo)return -1;
for(i=1;i<=NV;++i)id[i]=-1,ret+=in[i];
for(cnt=0,i=1;i<=NV;++i)
if(id[i]<0)
{
r=0,j=i;
while(j>=0&&id[j]<0)
{
if(id[j]==-2)
{
id[j]=++cnt;
while(q[--r]!=j)id[q[r]]=cnt;
}
else id[q[r++]=j]=-2,j=pre[j];
}
while(r--)id[q[r]]=++cnt;
}
if(cnt==NV)break;
for(i=0;i<NE;++i)
{
j=t[i],s[i]=id[s[i]],t[i]=id[t[i]];
if(s[i]!=t[i])c[i]-=in[j];
}
NV=cnt;
root=id[root];
}
return ret;
}
void addedge(int u,int v,int cost,int &e)
{
s[e]=u; t[e]=v; c[e]=cost;
if(u!=v) e++;
}
int main()
{
int n,m,e,T,cas=0;
int from,to,cost;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m),--n;
e=0;
while(m--)
{
scanf("%d%d%d",&from,&to,&cost);
addedge(from,to,cost,e);
}
ans=Directed_MST(0,n,e); // 0为源点 , 数据输入为 0 - n-1 , e-1条边
if(ans<0)printf("Case #%d: Possums!\n",++cas);
else printf("Case #%d: %d\n",++cas,ans);
}
return 0;
}
最小树形图
最新推荐文章于 2021-08-17 19:38:13 发布