题目:

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
题意描述:
题目还是有点意思的,但是还是改变不了使水题的本质。
输入结点的个数以及每个结点的权值
计算并输出有特殊要求的最小生成树
解题思路:
属于最小生成树问题,按照数据的格式,使用Kruskal算法。
代码实现:
 #include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct edge
{
int u,v,w;
};
struct edge e[*];//大数组申请全局变量
int f[];
bool cmp(struct edge x,struct edge y)
{
return x.w<y.w;
}
int getf( int v);
int merge(int c,int u);
int isp(int n); int main()
{
int t,i,n,c[],j,k,count,sum;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=;i<=n;i++)
scanf("%d",&c[i]);
k=;
for(i=;i<=n;i++)
{
for(j=i+;j<=n;j++)
{
if(isp(c[i]) || isp(c[j]) || isp(c[i]+c[j]))
{
e[k].u=i;
e[k].v=j;
e[k++].w = min(min(c[i],c[j]),abs(c[i]-c[j]));
}
}
}
sort(e+,e+k,cmp);
for(i=;i<=n;i++)
f[i]=i;
count = ;
sum=;
for(i=;i<k;i++)
{
if( merge(e[i].u,e[i].v) )
{
count++;
sum += e[i].w;
}
if(count == n-)
break;
} if(count == n-)
printf("%d\n",sum);
else
printf("-1\n");
}
return ;
} int getf( int v)
{
if(f[v]==v)
return v;
else
{
f[v]=getf(f[v]);
return f[v];
}
}
int merge(int v,int u)
{
int t1,t2;
t1=getf(v);
t2=getf(u);
if(t1 != t2)
{
f[t2]=t1;
return ;
}
return ;
}
int isp(int n)
{
if(n==)//1不是素数
return ;
int k,i;
k=(int)sqrt(n);
for(i=;i<=k;i++)
{
if(n % i==)
return ;
}
return ;
}

易错分析:

1、程序直接强制结束,可能是数组开的太大,放在全局变量的位置就可以了。

2、判断素数的过程中,1不是素数(代码功力)

最新文章

  1. phalcon3.0.1默认多模块生成的几个bug
  2. JAVASCRIPT常用API总结
  3. CSS的三种引入方式
  4. 四、优化及调试--网站优化--Yahoo军规下
  5. ios 7.1 7.1.1 半完美越狱后 电脑訪问手机越狱文件夹的方法
  6. HDU_1241——石油探索DFS
  7. lesson - 8 课程笔记 tar / gzip /bzip2 / xz /
  8. Go开发之路 -- 流程控制
  9. 翻译:insert on duplicate key update(已提交到MariaDB官方手册)
  10. 【Redis】2、CentOS 7 上安装 redis3.2.3安装与配置
  11. @ModelAttribute
  12. Jenkins ChangeLog
  13. _vimrc(VimScript脚本语言学习)
  14. 利用反射创建User类的对象
  15. 读入excle
  16. 小刘的机器学习---SVM
  17. 216. 组合总和 III
  18. Spinner的用法
  19. 磁贴界面颜色 Metro UI Colors
  20. Android解析WindowManagerService(二)WMS的重要成员和Window的添加过程

热门文章

  1. JMeter集合点
  2. MarkDown的用法
  3. Java笔记:开发环境
  4. java 连接 postgresql
  5. MicroPython支持的开发板:高性能、低成本创客首选
  6. table左边固定-底部横向滚动条
  7. ubuntu14.04下部署Tsung
  8. docker:(3)docker容器挂载宿主主机目录
  9. java.lang.Exception: 资源处理失败,失败原因:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column &#39;?????‰&#39; in &#39;where clause&#39;
  10. 【转载】MySQL5.6.27 Release Note解读(innodb及复制模块)