Tree 【最小生成树】

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<bits/stdc++.h>
#define  LL long long
using  namespace std;

const  int MAXN = 1e5;
const  int  MAXM = 1e8;
const  double PI = acos(-1.0);
const double e =exp(1.0);
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
/*-------------------------------*/
struct Edge{
    int from,to,val;
}edge[MAXM];
int cost[MAXN];
int n,m;
bool Issu(int x){
    if(x==1) return 0;
    int  k=sqrt(x);
    int i,j;
    for( i=2;i<=k;i++){
        if(x%i==0) break;
    }
    return i==k+1;
}
bool pan(int a,int b){
    return (Issu(a)||Issu(b))||Issu(a+b);
}
bool cmp(Edge a,Edge b){
    return a.val<b.val;
}
int par[MAXN];int top;
int  Find(int x){return x==par[x]?x:par[x]=Find(par[x]);}
void init(){
    for(int  i=0;i<=n;i++)
        par[i]=i;
    top=0;
}
void getmap(){
    for(int i=1;i<=n;i++)
          cost[i]=read();

    for(int  i=1;i<=n;i++){
        for(int  j=i+1;j<=n;j++){
            if(pan(cost[i],cost[j])){
                Edge e={i,j,min(min(cost[i],cost[j]),abs(cost[i]-cost[j]))};
                edge[top++]=e;
            }
        }
    }
}
void  krus(){
    int sum=0;
    sort(edge,edge+top,cmp);
    int i,j;int  k=0;
    for(i=0;i<top;i++){
        Edge  e=edge[i];
        if(Find(e.from)!=Find(e.to)){
            sum+=e.val;
            par[Find(e.from)]=Find(e.to);
             k++;
            if(k==n-1) break;
        }
    }
    for( i=2;i<=n;i++)
        if(Find(i)!=Find(1)) break;
    if(i==n+1) printf("%d\n",sum);
    else printf("-1\n");
}
int  main(){
    int t;cin>>t;
    while(t--){
       n=read();
        init();
        getmap();
        krus();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值