HDU1863(Kruskal+并查集水题)
2024-10-14 04:52:40
https://cn.vjudge.net/problem/HDU-1863
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
Input测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
Output对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
Sample Input
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100
Sample Output
3
?
#include<bits/stdc++.h>
#define maxn 110
using namespace std;
int n,m,tot;
int parent[maxn];
int ans;
struct edge
{
int u,v,w;
}EV[];
bool cmp(edge a,edge b)
{
return a.w<b.w;
}
int Find(int x)
{
if(parent[x]==-)
return x;
else
return Find(parent[x]);
}
void kruskal()
{
memset(parent,-,sizeof parent);
sort(EV+,EV+m+,cmp);
for(int i=;i<=m;i++)
{
int t1=Find(EV[i].u);
int t2=Find(EV[i].v);
if(t1!=t2)
{
ans+=EV[i].w;
parent[t1]=t2;
tot++;
}
}
}
int main()
{
while(~scanf("%d%d",&m,&n)&&m)
{
for(int i=;i<=m;i++)
cin>>EV[i].u>>EV[i].v>>EV[i].w;
ans=;
tot=;
kruskal();
if(tot!=n-)
cout<<"?"<<endl;
else
cout<<ans<<endl;
}
return ;
}
最新文章
- expected an indented block
- 千万用户级别应用系统背后的SOA组件化容器
- Raising Error Conditions with MySQL SIGNAL / RESIGNAL Statements
- [python]用Python进行SQLite数据库操作
- Linux下cutecom使用USB转串口线
- Unity 跑酷Demo难题总结
- TCP协议中的三次握手和四次挥手
- HTTP Post请求过程详解
- ASP.NET Redis 开发(转载)
- java Scanner与BufferedReader读取键盘输入性能比较
- 【HDOJ】3832 Earth Hour
- [TypeScript] Installing TypeScript and Running the TypeScript Compiler (tsc)
- Show Global Status 整理
- angularJS服务一
- JS控制菜单样式切换
- javascript创建类的6种方式
- 第21章 策略模式(Strategy Pattern)
- 一步步优化JVM四:决定Java堆的大小以及内存占用
- docker启动异常driver not supported
- C. Brutality Educational Codeforces Round 59 (Rated for Div. 2) 贪心+思维