Tree 【最小生成树】

来源:互联网 发布:jsp mysql 编辑:程序博客网 时间:2024/05/29 14:59

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 longusing  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;}