HDU2682——最小生成树+素数判定

素数判定+最小生成树

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. 
InputThe first will contain a integer t,followed by t cases. 
Each case begin with a integer N,then N integer Vi(0<=Vi<=1000000).OutputIf 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


//
//  main.cpp
//  HDU2682
//
//  Created by jinyu on 2018/7/15.
//  Copyright © 2018年 jinyu. All rights reserved.
//

#include <iostream>
#include <algorithm>
using namespace std;

const int INF = 0x3f3f3f3f;
int arc[600+7][600+7];
int dist[600+7];
int visited[600+7];
int N = 2;

struct dingD{
    int vi;
    int index;
};

int isPrime(long long num)
{
    if(num<=1) return 0;
    if(num==2||num==3) return 1;    if(num%6!=1&&num%6!=5) return 0;
    for(long long i=5;i*i<=num;i+=6)
        if(num%i==0||num%(i+2)==0) return 0;
    return 1;
}

int Prim(int start){
    int sum = 0;
    for(int i = 0;i<N;i++){
        visited[i] = 0;
        dist[i] = arc[start][i];
    }
    visited[start] = 1;
    
    for(int i = 1;i<N;i++){
        int min = INF;
        int pos = start;
        for(int j = 0;j<N;j++){
            if(!visited[j] && dist[j] < min){
                min = dist[j];
                pos = j;
            }
        }
        visited[pos] = 1;
        sum+=dist[pos];
        if(min==INF)
            return -1;
        for(int k = 0;k<N;k++){
            if(dist[k] > arc[pos][k])
            {
                dist[k] = arc[pos][k];
            }
        }
    }
    
    return sum;
}

int main(){
    int t;
    cin>>t;
    while(t--){
        cin>>N;
        int nn = N;
        dingD d[600+7];
        while(nn--){
            int v;
            cin>>v;
            d[N-nn-1].index = N-nn-1;
            d[N-nn-1].vi = v;
        }
        for(int i = 0;i<N;i++){
            for(int j = 0;j<N;j++){
                if(isPrime(d[i].vi) || isPrime(d[j].vi) || isPrime(d[i].vi+d[j].vi) ){
                    arc[i][j] = min( min(d[i].vi,d[j].vi),abs(d[i].vi - d[j].vi) );
                }
                else if(i==j){
                    arc[i][j] = 0;
                }
                else
                    arc[i][j] = INF;
            }
        }
        
        cout<<Prim(0)<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41508508/article/details/81052176