hdu 2682

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


题意概括:给n个数Vi(0<=Vi<=1000000),这n个数的编号是从1到n的,如果任意两个数如果他们中有一个数是素数或者他们相加的值是素数,那么可以认为这两个数可以连接,权值Min(Min(VA , VB),|VA-VB|)。

解题思路:把符合情况的所有组合的编号权值存入结构体中,Kruskal算一遍。

错误分析:这一题输入的n个数Vi是有等于0的情况的,但是0不属于素数,但是这一题无论把0当成素数还是非素数可以AC。

代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define M 1500
#define N 1000000
int i,j,m,n,l;
int f[N*2],prime[N+100];

struct edge 
{
	int u,v,w;
}e[M*M];
void p()
{
	memset(prime,0,sizeof(prime));
	for(i=2;i<N+100;i++)
	{
		if(prime[i]==0)
		{
			for(j=i*2;j<N+100;j+=i)
			{
				prime[j]=1;
				
			}
		}
	}
	prime[1]=1;
}
int min(int a,int b)
{
	if(a>b)
		a=b;
	return a;
}
int abs(int a)
{
	if(a<0)
		a=-a;
	return a;
}
bool cmp(edge a,edge b)
{
	return a.w<b.w;
}
int getf(int u)
{
	if(f[u]==u)
	{
		return u;
	}
	else
	{
		f[u]=getf(f[u]);
		return f[u];
	}
}
int merge(int u,int v)
{
	int t1=getf(u);
	int t2=getf(v);
	
	if(t1!=t2)
	{
		f[t2]=t1;
		return 1;
	}
	return 0;
}
void Kruskal()
{
	int num=0,sum=0;
	for(i=0;i<=1000100;i++)
	{
		f[i]=i;
	}
	//printf("n=%d l=%d\n",n,l);
	for(int i=0;i<l;i++)
	{
		if(merge(e[i].u,e[i].v)!=0)
		{
		//	printf("u=%d v=%d\n",e[i].u,e[i].v);
			num++;
			sum+=e[i].w;
		}
	//	if(num==n-1)
		//	break;
	}
//	printf("%d\n",num);
	if(num==0)
	{
		printf("-1\n");
	}
	else
	printf("%d\n",sum);
	
	
}
int main()
{
	int t,a[1000];
	scanf("%d",&t);
	while(t--)
	{
		l=0;
		scanf("%d",&n);
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
		
		}
		p();
		for(i=1;i<=n-1;i++)
		{
			for(j=i+1;j<=n;j++)
			{
				if(prime[a[i]]==0||prime[a[j]]==0||prime[a[i]+a[j]]==0)
				{
					e[l].u=i;
					e[l].v=j;
					e[l].w=min(min(a[i],a[j]),abs(a[i]-a[j]));	
					l++;
				}
				
			}
		}
	
		sort(e,e+l,cmp);
		
		Kruskal();
	}
	
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值