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;}
阅读全文
0 0
- Tree 【最小生成树】
- HDU2682 Tree 最小生成树
- HDU2724 Tree【最小生成树】
- HDU2724 Tree【最小生成树】
- hdu4786Fibonacci Tree 最小生成树
- 最小生成树 tree(陈立杰)
- 最小生成树(minimum spanning tree)
- 最小生成树-Minimum Spanning Tree
- hdu 2682 Tree 最小生成树
- hdu 4786 Fibonacci Tree ( 最小生成树 )
- HDU 2682--Tree【最小生成树】
- BZOJ 2654 tree 二分+最小生成树
- hdoj 2682 Tree(最小生成树)
- HDU4786 Fibonacci Tree【最小生成树】
- hdu2489Minimal Ratio Tree 最小生成树
- 【bzoj2654】【tree】【二分+最小生成树】
- 【二分+最小生成树】bzoj2654 tree
- hdoj 2682 Tree 【最小生成树】
- php 抓取页面乱码
- Android框架--Glide图片框架
- IntelliJ IDEA 2017 完美注册方法
- [译] TF-api(1) tf.nn.max_pool
- Effective C++第七章-模板和泛型编程之模板中实现继承
- Tree 【最小生成树】
- ArcGIS Web Appbuilder代码改动为不需要protal步骤初探
- jsp页面中用绝对路径${pageContext.request.contextPath}出现错误,解决办法
- 安装TC2层出现的问题
- 不管你从事哪个行业你都应该了解的:2017十大突破性科技
- 在Matplotlib图中插入LaTex公式
- 真正的沉浸式模式状态栏
- LaTeX——errors
- ACID, CAP理论