欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hdu_2682_prime

程序员文章站 2022-05-03 19:58:32
...

Tree

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
mean
一个无向图中给你两点,a,b如果a 或者b 或者a+b是prime(素数) 那么a和b相连,距离为a,b,a+b中最小值
第一行给你T有t组案例,
第二行输入n 接下来有n个点的值
求最小生成树

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll N=(ll)1e6*2+10;
const ll inf=(ll)1e18;
ll num[N]= {0,0,1,1},mp[666][666],vis[N],d[N],n;
void get()
{
    ll i,j;
    for(i=3; i<(ll)1e6+5; i++)
    {
        num[i++]=1;
        num[i]=0;
    }
    for(i=3; i<(ll)1e6+5; i++)
        for(j=i+i; j<(ll)1e6+5; j+=i)
            num[j]=0;
}
ll prime(ll s)
{
    ll i,j,ans=0;
    for(i=0; i<n; i++)
    {
        d[i]=mp[s][i];
        vis[i]=0;
    }
    d[s]=0,vis[s]=1;
    for(i=0; i<n-1; i++)
    {
        ll mm=inf,k=0;
        for(j=0; j<n; j++)
        {
            if(!vis[j]&&d[j]<mm)
            {
                mm=d[j];
                k=j;
            }
        }
        if(mm==inf) return -1;
        ans+=mm;
        vis[k]=1;
        for(j=0; j<n; j++)
        {
            if(!vis[j]&&mp[k][j]<d[j])
               d[j]=mp[k][j];
        }
    }
    return ans;
}
int main()
{
    ll t,i,j,v[666];
    get();
    while(cin>>t)
    {
        while(t--)
        {
            scanf("%lld",&n);
            for(i=0; i<n; i++)
                scanf("%lld",v+i);
            for(i=0; i<=n; i++)
                for(j=0; j<=n; j++)
                    mp[i][j]=inf;
            for(i=0; i<n; i++)
                for(j=0; j<n; j++)
                {
                    if(num[v[i]]||num[v[j]]||num[v[i]+v[j]])
                        mp[i][j]=mp[j][i]=min(min(v[i],v[j]),abs(v[i]-v[j]));
                }
            ll tt=prime(0);
            cout<<tt<<endl;

        }
    }
    return 0;
}
相关标签: each

推荐阅读