Poj 2485 highways (prim minimal spanning tree)

Source: Internet
Author: User

For the two points connected by the longest edge in the final generated Minimum Spanning Tree, there is no shorter edge so that the two points are connected in any way.

For this question, the edge length of the longest edge in the Minimum Spanning Tree is the length of the edge connecting the entire graph.

It can be seen that you only need to make a minimum spanning tree to the longest side of the tree that is abstracted by the given city.

#include<bits/stdc++.h>using namespace std;int dist[1020],m[1020][1020];void prim(int n,int dist[],int m[][1020]){    bool p[1020];    for(int i=2;i<=n;i++)    {        p[i]=false;        dist[i]=m[1][i];    }    dist[1]=0,p[1]=true;    for(int i=1;i<=n-1;i++)    {        int min=INT_MAX,k=0;        for(int j=1;j<=n;j++)        {            if(!p[j]&&dist[j]!=0&&dist[j]<min)            {                min=dist[j];                k=j;            }        }        if(k==0)            return;        p[k]=true;        for(int j=1;j<=n;j++)        {            if(!p[j]&&m[k][j]!=0&&(dist[j]==0||dist[j]>m[k][j]))                dist[j]=m[k][j];        }    }}int main(){    int T,N,M;    scanf("%d",&T);    for(int kase=1;kase<=T;kase++)    {        scanf("%d",&N);        for(int i=1;i<=N;i++)            for(int j=1;j<=N;j++)            {                scanf("%d",&M);                m[i][j]=M;            }        prim(N,dist,m);        printf("%d\n",dist[max_element(dist+1,dist+N+1)-dist]);    }    return 0;}


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.