hdu 1879 裸最小生成树

这是一道裸的最小生成树问题,很适合用来入门,练模板。赫赫~~

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <ctime>
#include <cstring>
using namespace std;

struct ss {int to,s,next,w;};
ss e[10086];
int head[120];
int size;

int n;

bool c(const ss &a,const ss &b)
{
	//if(a.w!=b.w) 
	return a.w<b.w;
	//else return a.s<b.s;
}

int father[120];

int gefather(int v)
{
	if(father[v]==0) return v;
	  else return gefather(father[v]);
}

void comb(int a,int b)
{
	a=gefather(a);
	b=gefather(b);
    if(a!=b) father[a]=b;
}

void tjb(int x,int y,int z)
{
	size++;
	e[size].s=x;
	e[size].next=head[x];
	head[x]=size;
	e[size].to=y;
	e[size].w=z;
}
	
int main()
{
	
	while(cin>>n&&n!=0)
	{
		size=0;
		memset(head,0,sizeof(head));
		memset(e,0,sizeof(e));
		memset(father,0,sizeof(father));
		for(int i=1;i<=n*(n-1)/2;i++)
		{
			int x,y,a,b;
			cin>>x>>y>>a>>b;
			if(b==0) tjb(x,y,a);
			else tjb(x,y,0);
		}
		
		sort(e+1,e+1+size,c);
		int rep=0,ans=0;
		for(int i=1;i<=size;i++)
		{
			if(rep==n-1) break;
			if(gefather(e[i].s)!=gefather(e[i].to)) 
			{
			   comb(e[i].s,e[i].to);
			   rep++;
			   ans+=e[i].w;
		    }
		}
		cout<<ans<<endl;
	}
   return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值