标签:
题意:求使图成为连通图的最小代价
正解:kruskal最小生成树算法
又是一道模板水题,最小生成树直接水过。
//It is made by jump~ #include <iostream> #include <vector> #include <algorithm> #include <cstring> #include <cstdio> #include <cmath> using namespace std; int n,m,total,maxl; int father[311]; struct node{ int u,to,w; }jump[300011]; int getint() { int w=0,q=0; char c=getchar(); while((c<‘0‘ || c>‘9‘) && c!=‘-‘) c=getchar(); if (c==‘-‘) q=1, c=getchar(); while (c>=‘0‘ && c<=‘9‘) w=w*10+c-‘0‘, c=getchar(); return q ? -w : w; } bool cmp(node a,node b) { return a.w<b.w; } int find(int x){ if(father[x]!=x) father[x]=find(father[x]); return father[x]; } void hebing(int x,int y){ father[y]=x; } int main() { n=getint();m=getint(); for(int i=1;i<=m;i++) { jump[i].u=getint();jump[i].to=getint();jump[i].w=getint(); } for(int i=1;i<=n;i++) father[i]=i; sort(jump+1,jump+m+1,cmp); for(int i=1;i<=m;i++){ int r1=find(jump[i].u),r2=find(jump[i].to); if(r1!=r2) { hebing(r1,r2); if(jump[i].w>maxl) maxl=jump[i].w; total++; } } printf("%d %d",total,maxl); return 0; }
标签:
原文地址:http://www.cnblogs.com/ljh2000-jump/p/5493996.html