Tree
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1921 Accepted Submission(s): 561
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.
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).
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 ac代码:#include<stdio.h> #include<string.h> #include<math.h> #include<iostream> #include<algorithm> #define MAXN 10010 #define INF 0xfffffff #define min(a,b) (a>b?b:a) using namespace std; int pri[MAXN][MAXN]; int v[MAXN]; int dis[MAXN]; int n,sum; int a[MAXN]; int b[10000002]; void fun() { int i,j; b[1]=1; for(i=2;i<1000010*2;i++) { if(b[i]==0) { for(j=i+i;j<1000010*2;j+=i) { b[j]=1; } } } } void prime() { int i,j,k; int min; memset(v,0,sizeof(v)); for(i=1;i<=n;i++) dis[i]=pri[1][i]; v[1]=1; sum=0; for(i=0;i<n-1;i++) { min=INF; for(j=1;j<=n;j++) { if(v[j]==0&&dis[j]<min) { min=dis[j]; k=j; } } if(min==INF) break; v[k]=1; sum+=min; for(j=1;j<=n;j++) { if(v[j]==0&&dis[j]>pri[k][j]) dis[j]=pri[k][j]; } } if(i<n-2) sum=-1; } int main() { int i,j,t; fun(); scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=1;i<=n;i++) for(j=1;j<=n;j++) pri[i][j]=pri[j][i]=INF; for(i=1;i<=n;i++) { scanf("%d",&a[i]); } for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(b[a[i]]==0||b[a[j]]==0||b[a[i]+a[j]]==0) { pri[i][j]=pri[j][i]=min(min(a[i],a[j]),abs(a[i]-a[j])); } //printf("%d\n",pri[i][j]); } } prime(); printf("%d\n",sum); } return 0; }