标签:hdu 2682 tree 最小生成树 筛法求素数 prim
2 5 1 2 3 4 5 4 4 4 4 4
4 -1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 650
#define INF 1000000000
int graph[MAX][MAX] , value[MAX];
bool NotPrime[2001000] ;
int prim(int n)
{
int lowCost[MAX];
bool visited[MAX] ;
memset(visited,false,sizeof(visited)) ;
int sum = 0 ;
for(int i = 0 ; i < n ; ++i)
{
lowCost[i] = graph[0][i] ;
}
visited[0] = true ;
for(int i = 0 ; i < n-1 ; ++i)
{
int index = -1 , min = INF ;
for(int j = 0 ; j < n ; ++j)
{
if(!visited[j] && lowCost[j]<min)
{
index = j ;
min = lowCost[j] ;
}
}
if(index == -1)
{
if(i < n-1)
{
return INF ;
}
break ;
}
sum += min ;
visited[index] = true ;
for(int j = 0 ; j < n ; ++j)
{
if(!visited[j] && lowCost[j] > graph[index][j])
{
lowCost[j] = graph[index][j] ;
}
}
}
return sum ;
}
int min(int a , int b)
{
return a>b?b:a ;
}
int main()
{
int t ;
NotPrime[0] = NotPrime[1] = true ;
for(int i = 2 ; i < 2001000/2 ; ++i)
{
for(int j = 2 ; j*i < 2001000 ; ++j)
{
NotPrime[j*i] = true ;
}
}
scanf("%d",&t);
while(t--)
{
int n ;
scanf("%d",&n);
for(int i = 0 ; i < n ; ++i)
{
scanf("%d",&value[i]) ;
}
for(int i = 0 ; i < n ; ++i)
{
for(int j = 0 ; j < i ; ++j)
{
if(!NotPrime[value[i]] || !NotPrime[value[j]] || !NotPrime[abs(value[i]+value[j])])
{
graph[i][j] = graph[j][i] = min(min(value[i],value[j]),abs(value[i]-value[j])) ;
}
else
{
graph[i][j] = graph[j][i] = INF ;
}
}
graph[i][i] = 0 ;
}
int sum = prim(n) ;
if(sum == INF)
{
puts("-1");
}
else
{
printf("%d\n",sum) ;
}
}
return 0 ;
}hdu 2682 Tree 最小生成树~~~~水题一枚,,用到了筛法求素数,我竟然在格式上面PE了两次!!
标签:hdu 2682 tree 最小生成树 筛法求素数 prim
原文地址:http://blog.csdn.net/lionel_d/article/details/43927043