(HDU - 2682)Tree
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3020 Accepted Submission(s): 933
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
题目大意:两个城市的不开心值分别为va,vb,若va或va或va+vb是素数,则这两个城市可以连边,边权为min(min(va,vb),abs(va-vb)),问所有城市都连通的最小权值和。
思路:先用普通素数筛预处理处2000000以内的素数(因为有va+vb,所以需要2000000),然后就是符合题意的连边,裸最小生成树。
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
const int maxn=605;
int fa[maxn],a[maxn];
bool prime[2000005];
struct node
{
int u,v,w;
}edge[maxn*maxn];
bool cmp(node a,node b)
{
return a.w<b.w;
}
void getprime()
{
memset(prime,0,sizeof(prime));//素数为0
prime[0]=1,prime[1]=1;
for(int i=2;i<=2000000;i++)
if(!prime[i])
{
for(int j=i<<1;j<=2000000;j+=i)
prime[j]=1;
}
}
int check(int x,int y)
{
if(!prime[x]||!prime[y]||!prime[x+y]) return min(min(x,y),abs(x-y));
else return -1;
}
int find(int x)
{
if(x==fa[x]) return x;
else return fa[x]=find(fa[x]);
}
int main()
{
getprime();
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",a+i);
fa[i]=i;
}
int tot=0;
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
{
int w=check(a[i],a[j]);
if(w!=-1) edge[tot++]=(node){i,j,w};
}
sort(edge,edge+tot,cmp);
int ans=0,cnt=0;
for(int i=0;i<tot;i++)
{
int fu=find(edge[i].u),fv=find(edge[i].v);
if(fu!=fv)
{
cnt++;
fa[fu]=fv;
ans+=edge[i].w;
}
if(cnt==n-1) break;
}
if(cnt==n-1) printf("%d\n",ans);
else printf("-1\n");
}
return 0;
}