poj_2421_mst
Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Description
We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
Input
Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
Output
Sample Input
3
0 990 692
990 0 179
692 179 0
1
1 2
Sample Output
179 刚开始用kruskal,结果tle 了,可能是我的代码写挫了吧。改为prim,wa了,改了cost[u][v]=cost[v][u]
#include<cstdio>
#include<cstring>
const int INF=0x3f3f3f;
const int MAXN=110;//看清上限
bool vis[MAXN];
int lowc[MAXN];
int cost[MAXN][MAXN];
int prim(int n)
{
memset(vis,false,sizeof(vis));
int ans=0;
vis[1]=true;
for(int i=2;i<=n;i++)
lowc[i]=cost[1][i];
for(int i=2;i<=n;i++)//我开始这里写成了i=1;当然一直是return -1;
{
int minc=INF;
int p=-1;
for(int j=1;j<=n;j++)
if(!vis[j]&&lowc[j]<minc)
{
minc=lowc[j];
p=j;
}
if(minc==INF)
return -1;
ans+=minc;
vis[p]=true;
for(int j=1;j<=n;j++)
if(!vis[j]&&cost[p][j]<lowc[j])
lowc[j]=cost[p][j];
}
return ans;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int w;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cost[i][j]=INF;
for(int i=1;i<=n;i++)
{
lowc[i]=INF;
for(int j=1;j<=n;j++)
{
scanf("%d",&w);
if(w<cost[i][j])//只保存最小权值
cost[i][j]=w;
}
}
int m;
scanf("%d",&m);
int u,v;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
cost[u][v]=cost[v][u]=0;//这里不能只写cost[u][v]=0;
}
int ans=prim(n);
printf("%d\n",ans);//我忘了要\n
}
return 0;
}
poj_2421_mst的更多相关文章
随机推荐
- 《Java程序设计》第二次实验报告
20145220 <Java程序设计>第二次实验报告 课程:Java程序设计 指导教师:娄嘉鹏 实验日期:2016.04.12 实验名称:Java面向对象程序设计 实验内容 初步掌握单元测 ...
- C++@语句块
#include <iostream> using namespace std; int main() { { int x=1; cout << x << endl ...
- 为mysql在表的某一位置增加一列
如果想在一个已经建好的表中添加一列,可以用诸如: alter table t1 add column addr varchar(20) not null; 这条语句会向已有的表t1中加入一列addr, ...
- javascrip中的confirm小技巧
jsp页面中的一个标签: <a href="javascript:void(0)" onclick="confirmDelete('<%=request.ge ...
- 前端面试库_JS部分_02
今天小编做了一个伟大的决定-----把我的初恋追回来.她在我心中一直是美好的,以前也人渣过,脑袋发热过,到了现在才真的是想有一个人陪伴着我,我与她约定晚些相见,我相信这个时间不会很久,虽然三年没有联系 ...
- 【转】iOS开发拓展篇—静态库
原文网址:http://www.cnblogs.com/wendingding/p/3893095.html iOS开发拓展篇-静态库 一.简单介绍 1.什么是库? 库是程序代码的集合,是共享程序代码 ...
- 【转】iOS websocket 及时通讯实现
原文网址:http://blog.csdn.net/manyxh/article/details/48196209 2015-09-03 by 木易哥哥 开发一个类似QQ.微信的即时IM聊天功能,做到 ...
- docker学习2-安装实践
windows上安装docker后,默认自动在后台运行,右下角有docker图标,鼠标右键点击出现菜单 可以查看docker版本,对一些基本项进行设置如下: 安装及具体操作参见官方文档: https: ...
- unity3d中Find的用法
在unity3d中用Find可以直接查找组件 例子一: 该脚本时绑在main Camera上的,"/Scene/player"这是在Hierarchy目录下直接找寻Scene ...
- C++泛型编程原理
1.什么是泛型编程前面我们介绍的vector,list,map都是一种数据结构容器,容器本身的存储结构不同,各容器中存在的数据类型也可以不同.但我们在访问这些容器中数据时,拥有相同的方式.这种方式就叫 ...