Hduoj2682【最小生成树】

/*Tree 
Time Limit : 6000/2000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 24   Accepted Submission(s) : 9
Font: Times New Roman | Verdana | Georgia 
Font Size: ← →
Problem Description
There are N (2<=N<=600) cities,each has a value of happiness,we consider two cities A and B whose value of happiness are VA and VB,if VA 
is a prime number,or VB is a prime number or (VA+VB) is a prime number,then they can be connected.What's more,the cost to connecte two cities 
is Min(Min(VA , VB),|VA-VB|).
Now we want to connecte all the cities together,and make the cost minimal. 
Input
The first will contain a integer t,followed by t cases.
Each case begin with a integer N,then N integer Vi(0<=Vi<=1000000). 
Output
If the all cities can be connected together,output the minimal cost,otherwise output "-1"; 
Sample Input
2
5
1
2
3
4
5

4
4
4
4
4
Sample Output
4
-1

Author
Teddy 
Source
2009浙江大学计算机研考复试(机试部分)——全真模拟 */
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
int f[610], num[610];
struct road
{
	int a,b, dis;
}r[200000];
int min(int x, int y)
{
	return x<y?x:y;
}
int find(int x)
{
	if(x != f[x])
	{
		f[x] = find(f[x]);
	}
	return f[x];
}
int merge(int x, int y)
{
	x = find(x);
	y = find(y);
	if(x != y)
	{
		f[x] = y;
		return 1;
	}
	return 0;
}
bool isprime(int x)
{
	int i, k;
	if(x == 1)
	return false;
	for(i = 2; i * i <= x; ++i)
	if(x % i == 0)
	return false;
	return true;
}
int cmp(const void *a, const void *b)
{
	return (*(struct road*)a).dis - (*(struct road*)b).dis;
}
int main()
{
	int i, j, k, t, n, m;
	scanf("%d", &t);
	while(t--)
	{
		scanf("%d", &n);
		for(i = 1; i <= n; ++i)
		scanf("%d", &num[i]);
		for(i = 1; i <= n; ++i)
		f[i] = i;
		m = 0;
		for(i = 1; i <= n; ++i)//save teh map
		{
			for(j = i+1; j <= n; ++j)
			if(isprime(num[i]) || isprime(num[j]) || isprime(num[i] + num[j]))
			{
					r[m].dis = min(min(num[i], num[j]), abs(num[i] - num[j]));
					r[m].a = i;
					r[m++].b = j;
			}
		}
		k = 0;
		int ans = 0;
		qsort(r, m, sizeof(r[0]),cmp);
		for(i = 0; i < m; ++i)//check the map
		{
			if(merge(r[i].a, r[i].b))
			{
				ans += r[i].dis;
				k++;
			}
		}
		if(k == n-1)
		printf("%d\n", ans);
		else
		printf("-1\n");
	}
	return 0;
}

题意:给出n个城市,每个城市都有一个值,当a城市的值为素数或b城市的值为素数或a+b的值为素数,则这2个城市可连通,并且付出的代价为Min(Min(a, b),|a-b|).,求能将这n个城市连通的最小代价,若不能连通,则输出-1。

思路:标准的最小生成树,只是多了一些小细节,比如说素数判断,以及求出城市相连的最小代价,求出后依旧是标准的模板题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值