current position:Home>R7-2 minimum spanning tree construction (25 points)

R7-2 minimum spanning tree construction (25 points)

2022-02-03 00:55:08 CSDN Q & A

img


giegie People !!

sample input :
4 6
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5




Refer to the answer 1:

#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
int n,m;
int mp[50][50],book[50],dis[50],parent[50];
void prim()
{
for(int i=1;i<=n;i++)
{
dis[i]=mp[1][i];
if(mp[1][i]!=inf)
parent[i]=1;
}
int ans;
book[1]=1;
for(int i=1;i<n;i++)
{
int minn=inf,u;
for(int j=1;j<=n;j++)
{
if(!book[j]&&minn>dis[j])
{
u=j;
minn=dis[j];
}
}
book[u]=1;

    int x=parent[u];    int y=u;    int z=mp[parent[u]][u];    if(x>y)         swap(x,y);    printf("%d,%d,%d\n",x,y,z);        for(int v=1;v<=n;v++)    {        if(!book[v]&&dis[v]>mp[u][v])        {            dis[v]=mp[u][v];            parent[v]=u;        }        }}

}

int main()
{
memset(book,0,sizeof(book));
cin>>n>>m;
memset(mp,0x3f,sizeof(mp));
for(int i=1;i<=n;i++)
mp[i][i]=0;
for(int i=1;i<=m;i++)
{
int a,b,c;
cin>>a>>b>>c;
mp[a][b]=mp[b][a]=min(mp[a][b],c);
}
prim();
}




Refer to the answer 2:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202030055068107.html

Random recommended