HDU 1233 还是畅通工程 (最小生成树 )

时间:2023-03-08 22:32:26
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省*“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。 

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

题解:套模板

还是菜得一P啊

 #include <iostream>
#include <algorithm>
using namespace std;
const int maxn=;
int n,res,m;
int par[maxn];
struct node
{
int u,v,w;
}es[maxn];
int cmp(node x,node y)
{
return x.w<y.w;
}
void init()
{
for(int i=;i<maxn;i++) par[i]=i;
}
int Find(int x)
{
if(par[x]==x) return x;
else return Find(par[x]);
}
int deal()
{
init();
sort(es,es+m,cmp);
res=;
for(int i=;i<m;i++){
int u=es[i].u,v=es[i].v,w=es[i].w;
if(Find(u)==Find(v)) continue;
par[Find(u)]=Find(v);
res+=w;
}
return res;
}
int main()
{
while(cin>>n&&n){
m=n*(n-)/;
for(int i=;i<m;i++){
cin>>es[i].u>>es[i].v>>es[i].w;
}
cout<<deal()<<endl;
}
return ;
}

。。。。。。

 #include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define lowbit(x) (x&(-x))
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
#define MAX 100000000000000000
#define MOD 1000000007
#define pi acos(-1.0)
#define ei exp(1)
#define PI 3.141592653589793238462
#define INF 0x3f3f3f3f3f
#define mem(a) (memset(a,0,sizeof(a)))
typedef long long ll;
ll gcd(ll a,ll b){
return b?gcd(b,a%b):a;
}
bool cmp(int x,int y)
{
return x>y;
}
const int N=;
const int mod=1e9+;
int f[N];
struct edge
{
int u,v,w;
}a[N];
void init()
{
for(int i=;i<=N;i++)
f[i]=i;
}
int find1(int x)
{
if(x!=f[x])
f[x]=find1(f[x]);
return f[x];
}
bool cmp1(edge a,edge b)
{
return a.w<b.w;
}
int main()
{
std::ios::sync_with_stdio(false);
int n,m;
while(scanf("%d",&n)&&n){
init();
m=n*(n-)/;
for(int i=;i<m;i++)
scanf("%d %d %d",&a[i].u,&a[i].v,&a[i].w);
sort(a,a+m,cmp1);
int s=;
for(int i=;i<m;i++){
int u=a[i].u,v=a[i].v,w=a[i].w;
if(find1(u)==find1(v)) continue;
f[find1(u)]=find1(v);
s+=w;
}
printf("%d\n",s);
}
return ;
}