hdoj 2682 Tree

Tree

Time Limit: 6000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1861    Accepted Submission(s): 545


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
敲代码时有一个小地方没看到  结果一直RE纠结了俩小时,所以说要细心............
prime算法:
#include<stdio.h>
#include<math.h>
#define INF 0x3f3f3f
#define max 650
#include<string.h>
int lowdis[max],visit[max],map[max][max];
int city;
int sushu[1000100];
void prime()
{
	int j,i,min,mindis=0,next;
	memset(visit,0,sizeof(visit));
	for(i=1;i<=city;i++)
	{
		lowdis[i]=map[1][i];
	}
	visit[1]=1;
	for(i=2;i<=city;i++)
	{
		min=INF;
		for(j=1;j<=city;j++)
		{
			if(!visit[j]&&min>lowdis[j])
			{
				next=j;
				min=lowdis[j];
			}
		}
		if(min==INF)
		{
			printf("-1
");
			return ;
		}
		visit[next]=1;
		mindis+=min;
		for(j=1;j<=city;j++)
		{
			if(!visit[j]&&lowdis[j]>map[next][j])
			{
				lowdis[j]=map[next][j];
			}
		}
	}
	printf("%d
",mindis);
} 
int min(int a,int b)
{
	if(a>b)
	a=b;
	return a;
}
void biao()
{
	int i,j;
	memset(sushu,0,sizeof(sushu));
	for(i=2;i<=1000100;i++)
	{
		if(!sushu[i])
		{
			for(j=i*2;j<=1000100;j+=i)
			sushu[j]=1;
		}
	}
	sushu[1]=1;
}
int main()
{
	int n,i,j;
	int a[max];
	scanf("%d",&n);
	biao();
	while(n--)
	{
		scanf("%d",&city);
		for(i=1;i<=city;i++)
		{
			scanf("%d",&a[i]);
			for(j=1;j<=city;j++)
			{
				if(i==j)
				map[i][j]=0;
				else
				map[i][j]=map[j][i]=INF;
			}
		}
		for(i=1;i<=city;i++)
		{
			for(j=i+1;j<=city;j++)
			{
				if(!sushu[a[i]]||!sushu[a[j]]||!sushu[a[i]+a[j]])
				{
					map[i][j]=map[j][i]=min(min(a[i],a[j]),abs(a[i]-a[j]));
				}
			}
		}
		prime();
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/tonghao/p/4507577.html