<h1 style="color:#1A5CC8"> 还是畅通工程</h1><strong><span style="font-family:Arial;font-size:12px;color:green;font-weight:bold;">Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25547 Accepted Submission(s): 11347
</span></strong>
<div class="panel_title" align="left">Problem Description</div> <div class="panel_content">某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Input</div> <div class="panel_content">测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Output</div> <div class="panel_content">对每个测试用例,在1行里输出最小的公路总长度。
</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Sample Input</div><div class="panel_content"><pre><div style="font-family:Courier New,Courier,monospace;">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</div>
Sample Output
3 5Huge input, scanf is recommended.HintHint<pre name="code" class="html">经典的kruskal算法,数据的特殊性有个小技巧,先用并查集将已经存在的路,节点进行路径压缩到同一个父节点,然后再用kruskal就可以了,注意:不要用cin,会超时
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
#define N 105
struct node{
int from;
int to;
int value;
node (int i=0,int j=0,int k=0){
from=i;
to=j;
value=k;
}
};
priority_queue<node> p;
bool operator< (const node&x,const node &y){
return x.value>y.value;
}
int n;
int father[N];
int ans;
void kruskal();
int find(int x);
void union_set(int a,int b,int c);
int main(){
int a,b,c,d;
int i,j;
freopen("1.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
if (n==0)
break;
for (i=0;i<N;i++){
father[i]=i;
}
for (i=0;i<n*(n-1)/2;i++){
scanf("%d%d%d%d",&a,&b,&c,&d);
if (d){
father[find(b)]=find(a);//路径压缩(这里是关键)
}
p.push(node(a,b,c));
}
ans=0;
kruskal();
cout<<ans<<endl;
}
}
void kruskal(){
while (!p.empty()){
node temp=p.top();
p.pop();
union_set(find(temp.from),find(temp.to),temp.value);
}
}
int find(int x){
if (x!=father[x])
father[x]=find(father[x]);
return father[x];
}
void union_set(int a,int b,int c){
if (a==b)
return;
father[b]=a;
ans+=c;
}
解决求解最小公路总长度的问题,涉及最小生成树算法的应用。
1427

被折叠的 条评论
为什么被折叠?



