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的更多相关文章
随机推荐
- DELPHI WEBSERVICE
一.服务程序 1.依次选择 NEW -> OTHER -> WEB SERVICE -> SOAP SERVER APPLICATION -> ISAPI DYNAMIC LI ...
- 什么是域名?什么网站名?什么是URL?
域名,相信大家都不默认,也使用过无数次!比如: google.com.baidu.com.163.com等. 这时候,你可能要奇怪了,为什么小编没有在前面加上www? 因为正常情况下,不应该是www. ...
- 【P1835】小红花
很简单的题,然而我没想到,在NOIP上怎么办嘛QAQ 话说这题不知道怎么分类啊……先扔到玄学里边把…… 原题: Fj在圣诞节来临之际,决定给他的奶牛发一些小红花.现在Fj一共有N头奶牛,这N头牛按照编 ...
- javascrip中的confirm小技巧
jsp页面中的一个标签: <a href="javascript:void(0)" onclick="confirmDelete('<%=request.ge ...
- feature visualization from ipython notebook
Feature visualization from ipython notebook Wang Xiao 1. install anaconda2 from: https://www.continu ...
- Docker Resources
Menu Main Resources Books Websites Documents Archives Community Blogs Personal Blogs Videos Related ...
- android:ScrollView嵌套ListView的问题
在ScrollView中嵌套使用ListView,看起来ListView只会显示一行多一点,不能滑动.ListView的高度怎么改都有问题,与预期不符合.搜索了一些解决方案,我觉得最好不要用这样的设计 ...
- 方正S4101g笔记本电脑搜不到无线网络
方正S4101g这款笔记本的无线网卡有问题.不能识别高版本的WIFI信号.有时候链接上之后,就再也找不到无线网络信号了.有时候根本就找不到. 解决方法:把无线路由的发送模式和频率设置到最低.重启路 ...
- mfs-用户
http://blog.csdn.net/liuyunfengheda/article/details/5260278 MFS总结 http://bbs.chinaunix.net/thread-16 ...
- shell之变量与read
环境变量 set 环境变量可供shell以外的程序使用 shell变量 env shell变量仅供shell内部使用 set:显示(设置)shell变量 包括的私有变量以及用户变量,不同类的shell ...