Tree
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1754 Accepted Submission(s): 509
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
Author
Teddy
题目给的输出样例很具有迷惑性啊!!竟然只有一个换行,o(╯□╰)o
好啊,是我笨
看代码:
与君共勉
#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 ;
}
与君共勉