hdoj.2682 Tree【最小生成树】 2015/03/27

来源:互联网 发布:mac查看php安装目录 编辑:程序博客网 时间:2024/06/05 10:18

Tree

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


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
251234544444
 

Sample Output
4-1
#include<stdio.h>#include<math.h>#include<string.h>#define MAXN 610#define MAXNINT 0x3f3f3f3fint map[MAXN][MAXN];int city[MAXN],flag[MAXN];int low[MAXN],visited[MAXN];int t,n;int min(int a,int b){int c = fabs(a-b);if( a<b && a<c )return a;if( b<a && b<c )return b;return c;}int sushu(int n){if( n == 1 || n == 0 ) return 0;if( n == 2 ) return 1;for( int i = 2 ; i*i <= n ; ++i )if( n%i == 0 )return 0;return 1;}int prim(){int i,j,pos,min,result=0;memset(visited,0,sizeof(visited));visited[1] = 1;pos = 1;for( i = 1 ; i <= n ; ++i )if( i != pos )low[i] = map[pos][i];for( i = 1 ; i < n ; ++i ){min = MAXNINT;for( j = 1 ; j <= n ; ++j )if( visited[j] == 0 && min > low[j] ){min = low[j];pos = j;}result += min;visited[pos] = 1;for( j = 1 ; j <= n ; ++j )if( visited[j] == 0 && low[j] > map[pos][j] )low[j] = map[pos][j];}return result;}int main(){int i,j;scanf("%d",&t);while(t--){scanf("%d",&n);memset(map,0,sizeof(map));memset(flag,0,sizeof(flag));for( i = 1 ; i <= n ; ++i )scanf("%d",&city[i]);for( i = 1 ; i < n ; ++i )for( j = i+1 ; j <= n ; ++j ){if( i == j )continue;if( sushu(city[i]) || sushu(city[j]) || sushu(city[i]+city[j]) ){map[i][j] = map[j][i] = min(city[i],city[j]);flag[i]++;flag[j]++;}else map[i][j] = map[j][i] = MAXNINT;}int is = 1 ;for( i = 1 ; i <= n ; ++i )if( flag[i] == 0 ){is = 0;break;}if( is )printf("%d\n",prim());else printf("-1\n");}return 0;}


0 0