Query the set + priority_queu + Kruskal to implement the Minimum Spanning Tree.

Source: Internet
Author: User
#include<stdio.h>#include<queue>using namespace std;#define MAX 99999int father[MAX];struct Edge{  int a;  int b;  int dist;  bool operator<(const Edge & e) const  {       if(dist>e.dist)         return true;    return false;  }}edge[MAX];void init(int n){  for(int i=1;i<=n;i++)  {     father[i]=i;  }}int find(int x){  while(x!=father[x])  {     x=father[x];  }  return x;}void merge(int a,int b){    int i=find(a);    int j=find(b);    if(i!=j)    {       father[i]=j;    }}int main(){    int n,m;    int a,b,d;    Edge tmp;    priority_queue<Edge> q;    while(scanf("%d%d",&n,&m)!=EOF)    {       init(n);       for(int i=0;i<m;i++)       {          scanf("%d%d%d",&tmp.a,&tmp.b,&tmp.dist);          q.push(tmp);       }       int sum=0;       while(!q.empty())       {          tmp = q.top();          //printf("11%d %d %d\n",tmp.a,tmp.b,tmp.dist);          int a=find(tmp.a);          int b=find(tmp.b);          if(a!=b)          {             merge(a,b);             printf("%d %d\n",tmp.a,tmp.b);             sum+=tmp.dist;          }          q.pop();       }       printf("%d\n",sum);    }    getchar();    return 0;} 


Query the set + priority_queu + Kruskal to implement the Minimum Spanning Tree.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.