[Prim + kruscal] Minimum Spanning Tree Template

Source: Internet
Author: User

Source: dlut oj1105: Zhuo's dreamtime limit: 1 sec memory limit: 128 MB
Submit: 40 solved: 14
[Submit] [Status] [web board] Description

Zhuo is a lovely boy and always make day dream. This afternoon he has a dream that he becomes the king of a kingdom called twobee.

In the dream Zhuo faced a hard situation: He shoshould make a traffic construction plan for the kingdom. we have known that the kingdom consists of N cities and M dirt roads, it's very uncomfortable when traveling in the road. now he wocould choose some roads to rebuild to Concrete Road. to avoid called twobee by the common people, Zhuo wants to show some excellent thing to this world while it needs your help. he wants his plan achieve two goals:

1. We shoshould choose just N-1 roads to rebuild. After rebuild we can also travel between any two cities by the concrete roads.

2. We want to minimize the longest length among the chosen roads.

So you shoshould write a program to calculate the total length of the chosen roads.

Input

There are multiple test cases.

The first line contains two integers n and M. (1 <= n <= 100, 1 <= m <= 10000)

In the next M lines, each line contains three integers a, B, W, indicating that there is a dirt road between City A and City B with length W. (1 <= A, B <= N, 1 <= W <= 1000)

Output

For each test case, output an integer indicating the total length of the chosen roads. If there is no solution, please output-1.

Sample Input
3 3
1 2 1 1 3 1 2 3 3
Sample output
2
Hintsource

Rainy

 

 

 

Prim algorithm

#include <cstdio>#include <iostream>#include <memory.h>using namespace std;const int maxn=102;const int inf=1<<30;int map[maxn][maxn];int dis[maxn];bool flag[maxn];int a,b,c,n,m,ans; void init(){    memset(map,-1,sizeof(map));    for(int i=0;i<m;i++)    {        scanf("%d%d%d",&a,&b,&c);        if(map[a][b]==-1 || c< map[a][b])        {            map[a][b]=map[b][a]=c;        }    }} void prim(){    memset(flag,false,sizeof(flag));    for(int i=1;i<=n;i++)dis[i]=inf;    dis[1]=0;    ans=0;    for(int j=1;j<=n;j++)    {        int now,value=inf;        for(int i=1;i<=n;i++)        {            if(flag[i]==false && dis[i]<value)            {                value=dis[i];                now=i;            }        }        if(value==inf)        {            cout << "-1" <<endl;            return;        }        flag[now]=true;        ans+=dis[now];        for(int i=1;i<=n;i++)        {            if(!flag[i] && map[now][i]!=-1 && dis[i]>map[now][i])            dis[i]=map[now][i];        }    }     cout << ans <<endl;} int main(){    //‘freopen("in.txt","r",stdin);    while(cin >> n >> m)    {        init();        prim();    }    return 0;}

 

 

 

 

The following is the Kruskal algorithm of the Minimum Spanning Tree. The principle of this algorithm looks complicated, but it is easy to implement: At the beginning, each vertex is a tree and edges are sorted in ascending order by weight. Then select an edge in the ascending order. If the two vertices of the selected edge are divided into two different trees, the edge is added to the Minimum Spanning Tree, merge the two vertices connected by the current edge. If the two vertices of the edge are in the same tree, no processing is performed. Note that this algorithm is applicable to undirected connected graphs, if it is a finite graph, you need to do some processing in the algorithm, but the algorithm principle is the same. kruskal算法:
#include <cstdio>#include <iostream>#include <memory.h>#include <algorithm>using namespace std;const int maxn=10002;int m,n;int cnt,length;int parent[maxn]; struct node{    int from;    int to;    int val;}s[maxn]; bool cmp(const node &l,const node &r){    return l.val<r.val;} void init(){    for(int i=0;i<maxn;i++)    {        parent[i]=i;    }} int find(int x){    while(x!=parent[x])    {        x=parent[x];    }    return x;} void merge(int a,int b,int val){    int roota=find(a);    int rootb=find(b);    if(roota!=rootb)    {        cnt++;        parent[rootb]=roota;        length+=val;    }} void kruskal(){    sort(s,s+n,cmp);    for(int i=0;i<n;i++)    {        merge(s[i].from,s[i].to,s[i].val);        if(cnt==m-1)break;    }    if(cnt<m-1)    {        length=-1;    }} int main(){   // freopen("in.txt","r",stdin);    while(cin >> m >> n)    {        init();        cnt=0,length=0;        memset(s,0,sizeof(s));        for(int i=0;i<n;i++)        {              cin >> s[i].from >> s[i].to >> s[i].val;        }       kruskal();        cout << length <<endl;    }    return 0;}

 

[prim + kruscal] Minimum Spanning Tree template

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.