MST | ||||||
| ||||||
Description | ||||||
既然大家都不愿意做水题,元帅也很无奈,想了好久也不知道什么是水题,因为在元帅的眼里都是水题,他定义的非水题就是他做不出来的题。太囧了,随便弄个水的MST。 | ||||||
Input | ||||||
测试输入包含若干测试用例。每个测试用例的第1行给出顶点数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个顶点的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。 | ||||||
Output | ||||||
对于每个测试用例,输出MST的最小路径总长度。 | ||||||
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
| ||||||
Author |
我们需要知道每次选边的时候选择最小的边
并查集加贪心吧。。///hh练习用一下优先队列
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
struct coor
{
int x,y,d;
friend bool operator <(coor a,coor b)
{
return a.d>b.d;
}
};
int pre[10003];
priority_queue<coor>q;
int find(int x)
{
if(x!=pre[x])
return pre[x]=find(pre[x]);
else return x;
}
int ans=0;
void coin(coor x)
{
int a=find(x.x);
int b=find(x.y);
if(a!=b)
{
pre[a]=b;
// printf(" ans:%d %d\n",a,b);
ans+=x.d;
}
}
void init(int n)
{
for(int i=1; i<=n; i++)
{
pre[i]=i;
}
}
int main()
{
int n;
while(scanf("%d",&n)==1&&n)
{
init(n);
ans=0;
int m=n*(n-1)/2;
while(!q.empty())
q.pop();
coor a,b;
for(int i=1; i<=m; i++)
{
scanf("%d%d%d",&a.x,&a.y,&a.d);
q.push(a);
}
while(!q.empty())
{
b=q.top();
coin(b);
q.pop();
}
printf("%d\n",ans);
}
}