Graph Theory of 2144 Data Structure Experiment 9: Minimum Spanning Tree

Graph Theory of Data Structure Experiments 9: Minimum Spanning Tree ...

Graph Theory of Data Structure Experiments 9: Minimum Spanning Tree

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

There are n cities, some of which can build roads between different cities. The cost of building different roads is different.Now we want to know how much it will cost to build roads to connect all the cities together so that any city can start and reach any other city.

Input

The input contains multiple sets of data in the following format.

The first line consists of two integers, n m, representing the number of cities and the number of roads that can be built.(n <= 100, m <=10000)

The remaining m rows have three positive integers a b c per row, which means that a road can be built between city a and city b at the cost of c.

Output

Each set of outputs takes up one line, with only the minimum cost of output.

Example Input 3 2 1 2 1 1 3 1 1 0 Example Output 2 0
#include<bits/stdc++.h> using namespace std; #define INF 0x3f3f3f3f int mmp[1010][1010]; bool visit[1010]; int lowcost[1010]; int m,n; int sum,flag; void prime() { int k; int temp; visit[1]=true; for(int i=1;i<=m;i++) lowcost[i]=mmp[i][1]; for(int i=2;i<=m;i++) { temp=INF; for(int j=1;j<=m;j++) { if(!visit[j]&&lowcost[j]<temp){ temp=lowcost[j]; k=j; } } /*if(temp==INF) { flag=1; break; }*/ visit[k]=true; sum+=temp; for(int j=1;j<=m;j++) { if(!visit[j]&&lowcost[j]>mmp[j][k]) lowcost[j]=mmp[j][k]; } } } int main() { int v,u,cost; while(cin>>m>>n) { memset(mmp,INF,sizeof(mmp)); memset(visit,false,sizeof(visit)); flag=0; sum=0; for(int i=0;i<n;i++) { cin>>v>>u>>cost; if(mmp[u][v]>cost) { mmp[v][u]= mmp[u][v]= cost; } } prime(); if(!flag)printf("%d\n",sum); //else printf("-1\n"); } }

6 July 2020, 10:28 | Views: 4873

Add new comment

For adding a comment, please log in
or create account

0 comments