Tree(并查集)
来源:互联网 发布:lua源码下载 编辑:程序博客网 时间:2024/04/29 19:01
Tree
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1771 Accepted Submission(s): 517
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.
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).
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
251234544444
Sample Output
4-1把满足题意的两点及最小花费。#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define M 1000010int notprime[M];int s[1000010];int f[M]; struct node{int a;int b;int c;}p[1000010];void fun(){int i,j;memset(notprime,0,sizeof(notprime));notprime[1]=1;for(i=2;2*i<M;i++){if(!notprime[i]){for(j=2*i;j<M;j+=i)notprime[j]=1;}}}bool cmp(node x,node y){return x.c<y.c;}int find(int x){return x==f[x]?x:f[x]=find(f[x]);}int bin(int x1,int x2,int x3){int t1,t2,x4=0;t1=find(x1);t2=find(x2);if(t1!=t2){f[t1]=t2;x4+=x3;}return x4;}int main(){int T;fun();scanf("%d",&T);while(T--){int n,m;int i,j,k=0;memset(p,0,sizeof(p));scanf("%d",&n);for(i=1;i<=n;i++){f[i]=i;scanf("%d",&s[i]);}for(i=1;i<=n;i++){ // f[i]=i;//scanf("%d",&s[i]);//不能这样写。会超时的 for(j=1;j<i;j++){if(!notprime[s[i]]||!notprime[s[j]]||!notprime[s[i]+s[j]]){p[k].a=i;p[k].b=j;//f[i]=j;p[k++].c=min(min(s[i],s[j]),abs(s[i]-s[j]));}}}sort(p,p+k,cmp);//for(i=0;i<k;i++){//printf("%d %d %d\n",p[i].a,p[i].b,p[i].c);//}int sum=0;for(i=0;i<k;i++){ if(find(p[i].a)!=find(p[i].b)) sum+=bin(p[i].a,p[i].b,p[i].c); } int l=0; for(i=1;i<=n;i++){ if(f[i]==i) l++; } if(l>1) printf("-1\n"); else printf("%d\n",sum);} }
0 0
- Tree(并查集)
- hdu5606 tree 并查集
- hdu5606 Tree (并查集)
- 【并查集】Is it a tree?
- 【并查集】Is it A Tree?
- 并查集,贪心:Color A Tree
- 【并查集】 HDOJ 4786 Fibonacci Tree
- Is It A Tree?(并查集)
- HDU 5200 Tree (离线并查集)
- hdu 4786 Fibonacci Tree(并查集)
- hdoj tree 5606 (并查集)
- hdoj 5606 tree 【并查集】
- HDOJ 5606 tree(并查集)
- 【并查集】HDOJ tree 5606
- HDU 5606 tree(并查集)
- hdoj--5606--tree(并查集)
- Aizu - 2564 Tree Reconstruction 并查集
- hdoj 5606 tree 【并查集】
- Linux系统调用程序分析
- 前端试题
- 我的java学习笔记(4)关于方法参数传递
- 密码截取
- 配置 log4j 详解
- Tree(并查集)
- 如何在Windows操作系统中搭建redis环境
- Hello,csdn.Hello,bolg.
- 蓝桥杯 21位的水仙花数
- Java中自定义枚举(Enum)项的值及int和Enum的互相转换
- Javascript 一些有趣的小地方
- button上面加推送的红点封装
- 【DP】 HDOJ 4734 F(x)
- 公开课机器学习笔记(2)欠拟合与过拟合