首页 > 代码库 > HDOJ--2682--Tree
HDOJ--2682--Tree
Tree
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2021 Accepted Submission(s): 584
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
2 5 1 2 3 4 5 4 4 4 4 4
Sample Output
4 -1
题意:基本都能看懂题们就不絮絮叨叨了。
思路:注意。一定要用打表。不然就会一直wa 甚至我都没有超时。而是一直wa无语。
上代码:
#include<stdio.h> #include<math.h> #include<string.h> #define INF 0x3f3f3f3f #define min(a,b) a<b?a:b int n,vis[601],map[601][601],dis[601],flag,sum,prim[1000010]; void fun(){ memset(prim,0,sizeof(prim)); for(int i=2;i<=1000010;i++) if(!prim[i]) for(int j=i*2;j<=1000010;j+=i) prim[j]=1; prim[1]=1; } void prime(){ memset(vis,0,sizeof(vis));//标记函数没有初始化。 int i; for(i=1;i<=n;i++) dis[i]=map[1][i]; vis[1]=1; flag=0; sum=0; for(i=1;i<n;i++){ int temp=INF,j,k; for(j=1;j<=n;j++) if(vis[j]==0&&dis[j]<temp) temp=dis[k=j]; if(temp==INF){ flag=1; break; } sum+=temp; vis[k]=1; for(j=1;j<=n;j++) if(vis[j]==0&&dis[j]>map[k][j]) dis[j]=map[k][j]; } } int main(){ int T,a[601]; scanf("%d",&T); while(T--){ memset(map,INF,sizeof(map)); scanf("%d",&n); fun(); for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++) if(!prim[a[i]]||!prim[a[j]]||!prim[a[j]+a[i]]){ int l=min(a[i],a[j]); int l2=min(l,abs(a[i]-a[j])); map[i][j]=map[j][i]=l2; } prime(); if(flag) printf("-1\n"); else printf("%d\n",sum); } return 0; }
HDOJ--2682--Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。