码迷,mamicode.com
首页 > 其他好文 > 详细

hdoj Tree

时间:2015-03-31 09:05:49      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:hdoj tree

Tree

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


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
 
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define MAX 2000020
#define inf 0x3f3f3f3f
using namespace std;
int isprime[MAX],map[610][610],low[610],v[610],vis[610];
int min(int a,int b){
    return a<b?a:b;
} 
void count(){
    int i,j;isprime[1]=1;
    for(i=2;i*i<MAX;++i){
        if(isprime[i])continue;
        for(j=i*i;j<MAX;j+=i)
            isprime[j]=1;
    }
}
int prime(int n){
    int temp,result=0,i,j,pos=1;
    memset(vis,0,sizeof(vis));
    for(i=1;i<=n;++i)
        low[i]=map[pos][i];
    vis[pos]=1;
    for(j=1;j<n;++j){
        temp=inf;
        for(i=1;i<=n;++i){
            if(!vis[i]&&temp>low[i]){
                temp=low[i];pos=i;
            }
        }
        if(temp==inf)return -1;
        result+=temp;
        vis[pos]=1;
        for(i=1;i<=n;++i){
            if(!vis[i]&&low[i]>map[pos][i])
                low[i]=map[pos][i];
        }
    }
    return result;
}
int main()
{
    count();
    int t,i,n,m,j;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(i=1;i<=n;++i){
            scanf("%d",&v[i]);
        }
        memset(map,0x3f,sizeof(map));
        for(i=1;i<=n;++i){
            for(j=1;j<=n;++j){
                if(isprime[v[i]]==0||isprime[v[j]]==0||isprime[v[i]+v[j]]==0){
                    map[i][j]=min(min(v[i],v[j]),abs(v[i]-v[j]));
                }
            }
        }
        printf("%d\n",prime(n));    
    }
    return 0;
}


hdoj Tree

标签:hdoj tree

原文地址:http://blog.csdn.net/r1986799047/article/details/44760621

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!