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

hdoj 2682 Tree(最小生成树)

时间:2015-04-07 10:03:13      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:算法   acm   algorithm   c   

Tree

http://acm.hdu.edu.cn/showproblem.php?pid=2682
Time Limit: 6000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1855    Accepted Submission(s): 544


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
 

Author
Teddy
 

Source
 
//最小生成树  标准版

#include<cstdio>

#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int M=1000001;
int pre[M];
int n[M];
int prime[M];
struct node
{
    int start;
    int end;
    int value;
}num[M];




int find(int x)
{
    return pre[x]==x?x:pre[x]=find(pre[x]);
}


void merge(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
      pre[fx]=fy;
}


int cmp(node a,node b)
{
    return a.value<b.value;



int main()
{
  memset(prime,0,sizeof(prime));
  __int64 i,j;
  prime[0]=prime[1]=1;
  for(i=2;i<1001;i++)
    if(!prime[i])
    for(j=i*i;j<M;j+=i)
      prime[j]=1;
      
  int t;
  scanf("%d",&t);
  while(t--)
  {
      int city,k;
      scanf("%d",&city);
      for(i=1;i<=city;i++)
      {
          scanf("%d",&n[i]);
          pre[i]=i;
      }
      
      k=0;
      memset(num,0,sizeof(num));
      for(i=1;i<=city;i++)
         for(j=i+1;j<=city;j++)
         if(!prime[n[i]]||!prime[n[j]]||!prime[n[i]+n[j]])
         {
             num[k].start=i;
             num[k].end=j;
             num[k].value=min(min(n[i],n[j]),abs(n[i]-n[j]));
             k++;
         }

    
    sort(num,num+k,cmp);
    __int64 ans=0;
    for(i=0;i<k;i++)
    {
      
      int fx=find(num[i].start);
      int fy=find(num[i].end);
       if(fx!=fy)
       {
           merge(fx,fy);
        ans+= num[i].value;
       }
    }

    
    int count=0;
    for(i=1;i<=city;i++)
    {
       
if(pre[i]==i)
         count++;
         if(count>1)
           break;    

    }
    if(count>1)
      printf("-1\n");
      else
        printf("%I64d\n",ans);

        
  } 
  return  0;

hdoj 2682 Tree(最小生成树)

标签:算法   acm   algorithm   c   

原文地址:http://blog.csdn.net/lh__huahuan/article/details/44904979

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