Description
Input
Output
Sample Input
1 2 3
1 3 7
2 3 10
2 4 4
2 5 8
3 4 6
3 5 2
4 5 17
Sample Output
連接4和5,2和5,2和3,1和3,花費17+8+10+7=42
HINT
Source
題解:
最大生成樹。不要問我爲什麼。。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN=20001;
struct xx
{
int from,to,w;
}e[MAXN<<1];
int father[MAXN],cnt,n,m;
long long tot=0;
bool cmp(xx a,xx b)
{
return a.w>b.w;
}
void add(int x,int y,int z)
{
cnt++;
e[cnt].from=x;
e[cnt].to=y;
e[cnt].w=z;
}
int find(int x)
{
if(x==father[x]) return x;
father[x]=find(father[x]);
return father[x];
}
void Kruskal()
{
int i=1,d=0;
while(i<=m&&d<n)
{
int x=e[i].from;
int y=e[i].to;
if(find(x)!=find(y))
{
father[find(x)]=find(y);
tot+=e[i].w;
d++;
}
i++;
}
if(d!=n-1) tot=-1;
}
int main(int argc, char *argv[])
{
int i,j,x,y,z;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++) father[i]=i;
for(i=1;i<=m;i++)
scanf("%d%d%d",&x,&y,&z),add(min(x,y),max(x,y),z);
sort(e+1,e+m+1,cmp);
Kruskal();
printf("%lld\n",tot);
return 0;
}