还是畅通project

                                             Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

                                                                     Total Submission(s): 32795    Accepted Submission(s): 14769

Problem Description
某省调查乡村交通状况。得到的统计表中列出了随意两村庄间的距离。省政府“畅通project”的目标是使全省不论什么两个村庄间都能够实现公路交通(但不一定有直接的公路相连。仅仅要能间接通过公路可达就可以),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 
Input
測试输入包括若干測试用例。每一个測试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行相应村庄间的距离,每行给出一对正整数,各自是两个村庄的编号。以及此两村庄间的距离。为简单起见,村庄从1到N编号。

当N为0时,输入结束,该用例不被处理。
 
Output
对每一个測试用例,在1行里输出最小的公路总长度。
 
Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
 
Sample Output
3
5

Huge input, scanf is recommended.
 
Source

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1233

解题思路:裸的最小生成树,克鲁斯卡尔,边权值排序。

代码例如以下:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define inf 1e9
const int maxn=10005;
int fa[maxn];
struct EG
{
int x,y,w;
}eg[maxn];
void get_fa()
{
for(int i=0;i<=maxn;i++)
fa[i]=i;
}
int find(int x)
{
return x==fa[x]?x:find(fa[x]);
}
void Union(int a,int b)
{
int a1=find(a);
int b1=find(b);
if(a1!=b1)
fa[a1]=b1;
}
int cmp(EG a,EG b)
{
return a.w<b.w;
}
int main(void)
{
int a,b,w,n;
while(scanf("%d",&n)!=EOF&&n)
{
get_fa();
int m=(n*(n-1))/2,ans=0;
for(int i=0;i<m;i++)
scanf("%d%d%d",&eg[i].x,&eg[i].y,&eg[i].w);
sort(eg,eg+m,cmp);
for(int i=0;i<m;i++)
{
if(find(eg[i].x)!=find(eg[i].y))
{
Union(eg[i].x,eg[i].y);
ans+=eg[i].w;
}
}
printf("%d\n",ans);
}
}

最新文章

  1. 安装自创建的windows服务。
  2. Zookeeper第一课 安装和配置
  3. 分享我用Qt开发的应用程序【二】在Qt应用程序中使用字体图标fontawesome
  4. 如何登录Google美国服务器
  5. UI开发核心问题-UI随屏幕自适应
  6. 如何通过WiFi来进行Android的真机模拟
  7. BCM策略路由交换芯片
  8. assert的基本用法
  9. NodeMCU透传数据到TcpServer和Yeelink平台
  10. (转)iOS-Runtime知识点整理
  11. VM11 CentOS6.7 i386 安装 oracle 11g r2
  12. Windows 修改域用户账户密码
  13. vue 特点
  14. 【托业】【新东方托业全真模拟】TEST09~10-----P5~6
  15. nginx负载均衡(反向代理)
  16. svn强制commit写log
  17. ctags相关
  18. Rails 添加新的运行环境
  19. T24银行核心业务系统
  20. ngBind {{}} ngBindTemplate

热门文章

  1. 编译impala、拓展impala语法解析模块
  2. View 和 ViewGroup 的 hasFocusable
  3. 2017.9.17校内noip模拟赛解题报告
  4. CSS3侧滑导航
  5. 基于CANopen DSP402的运动控制笔记
  6. cf B. Black Square
  7. Debounce 和 Throttle【转载】
  8. route---设置Linux内核中的网络路由表
  9. 【福利】微信小程序130个精选Demo合集
  10. Oracle HR 例子用户的建立 10g,11g均可