HDOJ 标题2682 Tree(最小生成树)
HDOJ 题目2682 Tree(最小生成树)
Total Submission(s): 1757 Accepted Submission(s): 511
Tree
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1757 Accepted Submission(s): 511
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
Author
Teddy
Source
2009浙江大学计算机研考复试(机试部分)——全真模拟
Recommend
lcy | We have carefully selected several similar problems for you: 2677 2683 2678 2676 2681
ac代码
#include<stdio.h> #include<string.h> #include<stdlib.h> #define INF 0xfffffff #define min(a,b) (a>b?b:a) int prime[1000010*2],a[1660],map[1010][1010],vis[1660],n; void fun() { int i,j; prime[1]=1; for(i=2;i<1000010*2;i++) { if(!prime[i]) { for(j=i+i;j<1000010*2;j+=i) { prime[j]=1; } } } } int prim() { int i,j; int sum=0; memset(vis,0,sizeof(vis)); vis[1]=1; for(i=1;i<n;i++) { int flag=-1; int min=INF; for(j=1;j<=n;j++) { if(!vis[j]&&map[1][j]<min) { min=map[1][j]; flag=j; } } if(flag==-1) break; sum+=map[1][flag]; vis[flag]=1; for(j=1;j<=n;j++) { if(!vis[j]&&map[1][j]>map[flag][j]) { map[1][j]=map[flag][j]; } } } if(i<n) return -1; else return sum; } int main() { int t; scanf("%d",&t); fun(); while(t--) { //int n; int i,j; scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&a[i]); } //memset(map,0,sizeof(map)); for(i=0;i<=n;i++) { for(j=0;j<=n;j++) map[i][j]=INF; } for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { if(!prime[a[i]]||!prime[a[j]]||!prime[a[i]+a[j]]) { map[i][j]=map[j][i]=min(min(a[i],a[j]),abs(a[i]-a[j])); } } } printf("%d\n",prim()); } }