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