zoukankan      html  css  js  c++  java
  • 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.
     

    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
     题意:基本都能看懂题们就不絮絮叨叨了。
    思路:注意。一定要用打表。不然就会一直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
    ");
    		else
    			printf("%d
    ",sum);	
    	}
    	return 0;
    }



  • 相关阅读:
    Jasmine入门
    最近面试js部分试题总结
    最近面试前端面试题整理(css部分)
    开发自己的类库
    关于FEer发展方向的思考
    工作那些事(八)工作的目标——《360周鸿祎在新员工入职培训上的讲话》读后感
    工作那些事(七)选择与被选择
    工作那些事(六)谈谈好的编程习惯的好处
    工作那些事(五)谈谈项目资料整理和积累
    工作那些事(四)大公司VS小公司
  • 原文地址:https://www.cnblogs.com/jhcelue/p/7131185.html
Copyright © 2011-2022 走看看