hdu 2682
来源:互联网 发布:菩提老祖就是如来知乎 编辑:程序博客网 时间:2024/05/16 18:39
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.
Each case begin with a integer N,then N integer Vi(0<=Vi<=1000000).
251234544444
4-1
题意概括:给n个数Vi(0<=Vi<=1000000),这n个数的编号是从1到n的,如果任意两个数如果他们中有一个数是素数或者他们相加的值是素数,那么可以认为这两个数可以连接,权值是Min(Min(VA , VB),|VA-VB|)。
解题思路:把符合情况的所有组合的编号权值存入结构体中,Kruskal算一遍。
错误分析:这一题输入的n个数Vi是有等于0的情况的,但是0不属于素数,但是这一题无论把0当成素数还是非素数可以AC。
代码:
#include<stdio.h>#include<math.h>#include<string.h>#include<algorithm>using namespace std;#define M 1500#define N 1000000int i,j,m,n,l;int f[N*2],prime[N+100];struct edge {int u,v,w;}e[M*M];void p(){memset(prime,0,sizeof(prime));for(i=2;i<N+100;i++){if(prime[i]==0){for(j=i*2;j<N+100;j+=i){prime[j]=1;}}}prime[1]=1;}int min(int a,int b){if(a>b)a=b;return a;}int abs(int a){if(a<0)a=-a;return a;}bool cmp(edge a,edge b){return a.w<b.w;}int getf(int u){if(f[u]==u){return u;}else{f[u]=getf(f[u]);return f[u];}}int merge(int u,int v){int t1=getf(u);int t2=getf(v);if(t1!=t2){f[t2]=t1;return 1;}return 0;}void Kruskal(){int num=0,sum=0;for(i=0;i<=1000100;i++){f[i]=i;}//printf("n=%d l=%d\n",n,l);for(int i=0;i<l;i++){if(merge(e[i].u,e[i].v)!=0){//printf("u=%d v=%d\n",e[i].u,e[i].v);num++;sum+=e[i].w;}//if(num==n-1)//break;}//printf("%d\n",num);if(num==0){printf("-1\n");}elseprintf("%d\n",sum);}int main(){int t,a[1000];scanf("%d",&t);while(t--){l=0;scanf("%d",&n);for(i=1;i<=n;i++){scanf("%d",&a[i]);}p();for(i=1;i<=n-1;i++){for(j=i+1;j<=n;j++){if(prime[a[i]]==0||prime[a[j]]==0||prime[a[i]+a[j]]==0){e[l].u=i;e[l].v=j;e[l].w=min(min(a[i],a[j]),abs(a[i]-a[j]));l++;}}}sort(e,e+l,cmp);Kruskal();}return 0;}
阅读全文
0 0
- HDU 2682
- hdu 2682
- hdu 2682
- hdu 2682 Tree
- hdu 2682 Tree
- HDU 2682 Tree
- hdu 2682 Tree
- hdu
- hdu
- HDU
- hdu ()
- hdu
- hdu
- HDU
- HDU
- hdu
- hdu
- HDU
- 子雨大数据之Spark入门教程
- SSH框架搭建
- TableView cell section TextField ALert
- PHP的高效率写法
- node.js 学习<一>
- hdu 2682
- CAS框架单点登录,自定义验证登录方式(添加系统标识)
- 使用宏的代码
- 1957-挂盐水的故事
- ANSYS 错误收集
- 数据库相关整理
- linux下的文件权限以及用户权限
- 51nod 1596搬货物 解题报告
- Android在代码中开启OpenGL 4xMSAA 抗锯齿