http://lightoj.com/volume_showproblem.php?problem=1059最小生成树变形

利用kruscal求最小生成树,如果建一条路的费用超过建一个机场,就去掉该边(这点很关键);

#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;
const __int64 N=10002;
const int INF=9999999999;
struct node
{
 __int64 u,v;
 __int64 cost;
}a[N*10];
__int64 fa[N],con[N],n,m,cs;
bool vis[N];
void init()
{ memset(vis,false,sizeof(vis));
	 for(__int64 i=0;i<N;i++)
	 {   
	    fa[i]=i;
	      
	    
	 }
}
bool cmp(node a,node b)
{
	return a.cost<b.cost;
}
int find(int x)
{
 return x==fa[x]?x:fa[x]=find(fa[x]);
}
int main()
{ /*freopen("1.txt","r",stdin);
freopen("2.txt","w",stdout); */ 
	int t;
	scanf("%d",&t);
	for(int i=1;i<=t;i++)
	{
		init();
	 printf("Case %d: ",i);
	 scanf("%d%d%d",&n,&m,&cs);
	 for(int j=1;j<=m;j++)
	 {
		 scanf("%d%d%lld",&a[j].u,&a[j].v,&a[j].cost);
		 
	 }
	 sort(a+1,a+m+1,cmp);
	 __int64 Con=0,cnt=0,res=0;
	 for(int j=1;j<=m;j++)
	 {
	  int xx=find(a[j].u),yy=find(a[j].v);
	  if(xx!=yy&&a[j].cost<cs)
	   {
		   
	       fa[xx]=yy;
		  
		  Con+=a[j].cost;
		  cnt++;
	    }
	 }
	 if(cnt==n-1)
	 {
	   printf("%lld 1\n",Con+cs);
	 }
	 else{
		//printf("n=%d\n",n);
		   printf("%lld ",(Con+(n-cnt)*cs));
		   printf("%lld\n",n-cnt);
		 }
	}
  return 0;
}/*
 5 3 100
 1 2 3
 2 4 1
 3 5 2
 */


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值