【最小生成树入门专题1】H

来源:互联网 发布:阿里云搭建mc服务器 编辑:程序博客网 时间:2024/05/22 06:40

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
251234544444
Sample Output
4-1




#include<stdio.h>#include<math.h>#include<stdlib.h>#include<string.h>#define inf 9999999 int e[1100][1100];int book[1100],a[1100];int dis[1100];int isprime[2010000];int Min(int a,int b){if( a<b)return a;return b;}int Prime(int n){int i;if(n ==1||n==2)return 0;for(i = 2; i *i <= n; i ++){if(n%i == 0)return 0;}return 1;}int main(){int t;int n,i,j,u,count,sum,min,flag;for(i = 1; i <= 2001000; i ++){isprime[i] = 1;}isprime[0] = isprime[1] = 0;for(i = 1; i*i <= 2001000; i ++){if(isprime[i]){for(j = i*2; j <= 2001000; j = j+i){isprime[j] = 0;}}}scanf("%d",&t);while(t--){memset(a,0,sizeof(a));        memset(dis,0,sizeof(dis));        memset(book,0,sizeof(book));        memset(e,0,sizeof(e));sum = count = 0;flag = 0;u = 0;scanf("%d",&n);for(i = 1; i <= n; i ++)scanf("%d",&a[i]);for(i = 1; i <= n; i ++)for(j = 1; j <= n; j ++){if(i == j)e[i][j] = 0;else if(isprime[a[i]]||isprime[a[j]]||isprime[a[i]+a[j]]){e[i][j] = Min(abs(a[i]-a[j]),Min(a[i],a[j]));e[j][i] = Min(abs(a[i]-a[j]),Min(a[i],a[j]));}else{e[i][j] = inf;e[j][i] = inf;}}for(i = 1; i <= n; i ++){dis[i] = e[1][i];}count ++;book[1] = 1;while(count < n){min = inf;for(i = 1; i <= n; i ++){if(!book[i]&&dis[i]<min){min = dis[i];u = i;}}book[u] = 1;sum = sum + dis[u];count ++;for(i = 1; i <= n; i ++){if(!book[i]&&dis[i]>e[u][i]){dis[i] = e[u][i];}}}for(i = 1; i <= n; i ++)if(book[i])flag++;if(flag != n)printf("-1\n");elseprintf("%d\n",sum);}return 0;}









阅读全文
0 0