码迷,mamicode.com
首页 > 其他好文 > 详细

(hdu step 6.1.5)继续畅通工程(求让n个点连通的最小费用)

时间:2015-03-10 14:00:05      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

题目:

继续畅通工程

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 173 Accepted Submission(s): 132
 
Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
 
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。

当N为0时输入结束。
 
Output

            每个测试用例的输出占一行,输出全省畅通需要的最低成本。
 
Sample Input
3
1 2 1 0
1 3 2 0
2 3 4 0
3
1 2 1 0
1 3 2 0
2 3 4 1
3
1 2 1 0
1 3 2 1
2 3 4 1
0
 
Sample Output
3
1
0
 
Author
ZJU
 
Source
浙大计算机研究生复试上机考试-2008年
 


题目分析:

              使用kruscal来求最小生成树。这道题的特点如下:

1)对已建边的处理方式:将其权值标记为0即可,如:edges[i].weight = 0;


需要注意的是,本题需要用C++提交。感觉杭电最近是不是有点问题啊。。。之前用G++提交一直好好的。


2)顺便重温了一下快排的写法:qsort(edges+1,cnt,sizeof(edges[1]),cmp1);



代码如下:

/*
 * e.cpp
 *
 *  Created on: 2015年3月10日
 *      Author: Administrator
 */

#include <iostream>
#include <cstdio>
#include <algorithm>


using namespace std;

const int maxn = 101;

struct Edge{
	int begin;
	int end;
	int weight;
}edges[maxn*maxn];

int father[maxn];

int n;

int find(int a){
	if(a == father[a]){
		return a;
	}

	return father[a] = find(father[a]);
}


int kruscal(int count){
	int i;
	for(i = 1 ; i <= n ; ++i){
		father[i] = i;
	}

	int sum = 0;
	for(i = 1 ; i <= count ; ++i){
		int fa = find(edges[i].begin);
		int fb = find(edges[i].end);

		if(fa != fb){
			father[fa] = fb;
			sum += edges[i].weight;
		}
	}

	return sum;
}

bool cmp(Edge a,Edge b){
	return a.weight < b.weight;
}


int cmp1(const void* a,const void* b){
	return ((Edge*)a)->weight > ((Edge*)b)->weight;//这样才是从小到大排序
}

int main(){
	while(scanf("%d",&n)!=EOF,n){
		int m = (n-1)*n/2;

		int cnt = 1;
		int i;
		for(i = 1 ; i <= m ; ++i){
			int flag;

			scanf("%d%d%d%d",&edges[cnt].begin , &edges[cnt].end , &edges[cnt].weight , &flag);


			if(flag == 1){
				edges[cnt].weight = 0;
			}

			cnt++;
		}

		cnt -= 1;


		sort(edges+1,edges+1+cnt,cmp);

//		qsort(edges+1,cnt,sizeof(edges[1]),cmp1);

		printf("%d\n",kruscal(cnt));
	}

	return 0;
}







(hdu step 6.1.5)继续畅通工程(求让n个点连通的最小费用)

标签:

原文地址:http://blog.csdn.net/hjd_love_zzt/article/details/44174117

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!