HDU 2682 Tree

时间:2023-03-09 02:33:22
HDU 2682 Tree

题目:

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.

InputThe first will contain a integer t,followed by t cases. 
Each case begin with a integer N,then N integer Vi(0<=Vi<=1000000).OutputIf 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
题意描述:
题目还是有点意思的,但是还是改变不了使水题的本质。
输入结点的个数以及每个结点的权值
计算并输出有特殊要求的最小生成树
解题思路:
属于最小生成树问题,按照数据的格式,使用Kruskal算法。
代码实现:
 #include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct edge
{
int u,v,w;
};
struct edge e[*];//大数组申请全局变量
int f[];
bool cmp(struct edge x,struct edge y)
{
return x.w<y.w;
}
int getf( int v);
int merge(int c,int u);
int isp(int n); int main()
{
int t,i,n,c[],j,k,count,sum;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=;i<=n;i++)
scanf("%d",&c[i]);
k=;
for(i=;i<=n;i++)
{
for(j=i+;j<=n;j++)
{
if(isp(c[i]) || isp(c[j]) || isp(c[i]+c[j]))
{
e[k].u=i;
e[k].v=j;
e[k++].w = min(min(c[i],c[j]),abs(c[i]-c[j]));
}
}
}
sort(e+,e+k,cmp);
for(i=;i<=n;i++)
f[i]=i;
count = ;
sum=;
for(i=;i<k;i++)
{
if( merge(e[i].u,e[i].v) )
{
count++;
sum += e[i].w;
}
if(count == n-)
break;
} if(count == n-)
printf("%d\n",sum);
else
printf("-1\n");
}
return ;
} int getf( int v)
{
if(f[v]==v)
return v;
else
{
f[v]=getf(f[v]);
return f[v];
}
}
int merge(int v,int u)
{
int t1,t2;
t1=getf(v);
t2=getf(u);
if(t1 != t2)
{
f[t2]=t1;
return ;
}
return ;
}
int isp(int n)
{
if(n==)//1不是素数
return ;
int k,i;
k=(int)sqrt(n);
for(i=;i<=k;i++)
{
if(n % i==)
return ;
}
return ;
}

易错分析:

1、程序直接强制结束,可能是数组开的太大,放在全局变量的位置就可以了。

2、判断素数的过程中,1不是素数(代码功力)