Tree(prime)

时间:2023-03-09 16:01:46
Tree(prime)

Tree

Time Limit : 6000/2000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 2   Accepted Submission(s) : 2
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
 题解:
就是给n个数,如果这个数跟另一个数的和或者这两个数有一个是素数就可以连接;权值为Min(Min(VA , VB),|VA-VB|).
注意要打素数表;
prime代码:
 #include<stdio.h>
#include <string.h>
#include<math.h>
#define Min(x,y) (x<y?x:y)
const int INF=0x3f3f3f3f;
const int MAXN=;
bool prim[];
int N,answer;
int judge(int a,int b){
if(!prim[a]||!prim[b]||!prim[a+b]){
return Min(Min(a,b),fabs(a-b));
}
else return -;
}
void pt(){
memset(prim,false,sizeof(prim));
prim[]=prim[]=true;
for(int i=;i<=;i++){
if(!prim[i])for(int j=i*i;j<;j+=i){
prim[j]=true;
}
}
}
int map[MAXN][MAXN],vis[MAXN],low[MAXN];
int v[MAXN];
void prime(){
int k;
int temp,flot=;
answer=;
memset(vis,,sizeof(vis));
vis[]=;
for(int i=;i<N;i++)low[i]=map[][i];
for(int i=;i<N;i++){
temp=INF;
for(int j=;j<N;j++)
if(!vis[j]&&temp>low[j])
temp=low[k=j];
if(temp==INF){
if(flot==N)printf("%d\n",answer);
else puts("-1");
break;
}
answer+=temp;
vis[k]=;
flot++;
for(int j=;j<N;j++)
if(!vis[j]&&low[j]>map[k][j])
low[j]=map[k][j];
}
}
int main(){
int T,t;
scanf("%d",&T);
while(T--){
pt();
memset(map,INF,sizeof(map));
scanf("%d",&N);
for(int i=;i<N;i++)scanf("%d",&v[i]);
for(int i=;i<N;i++)
for(int j=i+;j<N;j++){
t=judge(v[i],v[j]);
if(t>=){
if(t<map[i][j])map[i][j]=map[j][i]=t;
}
}
prime();
}
return ;
}