http://acm.hdu.edu.cn/showproblem.php?pid=2682
只能说数据很水。。。。。。练练prim模板,
Tree
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2076 Accepted Submission(s): 597
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
Source
#include <cstdio>
#include <vector>
#include <cstring>
#include <queue>
#define maxn 1000010
const int INF=1<<30;
using namespace std;
struct edge{
int v,w;
edge(int vv,int ww):v(vv),w(ww){}
edge(){}
friend bool operator <(const edge &a,const edge &b){
return a.w>b.w;
}
};
int n;
int a[maxn];
int pri[maxn];
bool used[maxn];
int dis[maxn];
vector<vector<edge> >G;
void get_prim(){
pri[0]=pri[1]=1;
for(int i=2;i<maxn;i++)
if(!pri[i])
for(int j=i+i;j<maxn;j+=i)
pri[j]=1;
}
int Min(int x,int y,int z){
if(x>y){
if(y>z)return z;
else return y;
}
else if(x>z)return z;
else return x;
}
int prim(int s){
priority_queue<edge> q;
memset(used,0,sizeof(used));
for(int i=0;i<n;i++)
dis[i]=INF;
dis[s]=0;
q.push(edge(s,0));
int ans=0,cnt=0;
while(!q.empty()){
edge p=q.top();
q.pop();
int u=p.v;
if(used[u])continue;
ans+=p.w;
cnt++;
used[u]=1;
if(cnt==n)return ans;
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i].v;
int w=G[u][i].w;
if(used[v]||dis[v]<=w)continue;
dis[v]=w;
q.push(edge(v,w));
}
}
return -1;
}
int main()
{
int t;
memset(pri,0,sizeof(pri));
get_prim();
scanf("%d",&t);
while(t--){
scanf("%d",&n);
G.clear();
G.resize(n+10);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
for(int i=0;i<n;i++){
int x=a[i];
for(int j=i+1;j<n;j++){
int y=a[j];
if(!(pri[x]&&pri[y]&&pri[x+y])){
int z=x-y>0?x-y:y-x;
G[i].push_back(edge(j,Min(x,y,z)));
G[j].push_back(edge(i,Min(x,y,z)));
// printf("%d %d %d\n",i,j,Min(x,y,z));
}
}
}
printf("%d\n",prim(0));
}
return 0;
}
AC之路,我选择坚持~~