浙江大学机试--继续畅通工程

时间:2019-01-31
本文章向大家介绍浙江大学机试--继续畅通工程,主要包括浙江大学机试--继续畅通工程使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目:牛客网链接

概述: 给定n个村庄,然后给出他们之间的路的长度和代价,和是否修好,问如何修路才能让代价最小,输出最小代价。

**思路:**本题采用最小生成树 Kruskal算法(并查集)。相关的知识可以百度一下。注释中写思路。

#include <iostream>
#include <algorithm>
using namespace std;

//用于并查集中使用,存放父节点 
int father[2000];

struct Edge{
	int a, b, status, cost;
};

bool cmp(Edge a, Edge b)
{
	if(a.status == b.status)
	{
		return a.cost < b.cost;
	}
	else
	{
		return a.status > b.status;
	}
}
//查找父节点 
int find_father(int x)
{
	while(x != father[x])
	{
		x = father[x];
	}
	return x;
} 


int main()
{
	int n;
	Edge edge[50000];
	
	while(scanf("%d", &n) != EOF && n != 0)
	{
		for(int i = 1; i <= n * (n - 1) / 2; i++)
		{
			scanf("%d%d%d%d",&edge[i].a,&edge[i].b,&edge[i].cost,&edge[i].status);
		} 
		sort(edge + 1, edge + 1 + n * (n -1) / 2, cmp);
		int ans = 0;
		for(int i = 1 ; i <= n ; i++)father[i] = i;
		for(int i = 1; i <= n * (n - 1) / 2; i++)
		{
			
			int a = find_father(edge[i].a);
			int b = find_father(edge[i].b);
			if( a != b)
			{
				father[a] = b;
				
				if(edge[i].status == 0) 
				{ans += edge[i].cost; 
				//cout << "链接了" << edge[i].a  <<" 和" << edge[i].b  <<"花费"<< edge[i].cost<< endl;
				} //只有状态为0才参与计算
			}	
		}
		printf("%d\n",ans);
		
	}
	
	
}