Smooth Traffic Project (minimum spanning tree) (shortest path)

Problem Description
Target provincial government "Smooth Traffic Project" is to make between any two villages in the province can achieve road traffic (but not necessarily directly connected to the road, as long as indirectly through the road up to). After investigation and assessment, statistics obtained a list of possible construction of several roads highway costs. Now you write a program to calculate the lowest cost needed to clear the province.
 

 

Input
Test input contains several test cases. The first row of each road test strip evaluation given number N, the number of villages M (<100); N subsequent
cost of correspondence between the village road rows each given a pair of positive integers, respectively, two villages the number and cost of road between these two villages (and a positive integer). For simplicity, the village numbered from 1 to M. When N is 0, all the input end, an output not corresponding results.
 

 

Output
For each test case, output the lowest cost needed to clear the province in a row. If the data is not sufficient to ensure the smooth flow statistics, output "?."
 

 

Sample Input
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
 

 

Sample Output
3 ?
 

Analysis: Prim algorithm (+ Dijkstra's shortest path and recording any two points)

Pit: To maximize the maximum initialize all the villages, because the number is subject to the village, but not the biggest village

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define s(x) scanf("%d",&x)
#define sc(x,y) scanf("%d %d",&x,&y)
#define sca(x,y,z) scanf("%d %d %d",&x,&y,&z)
const int mxn = 1e2+5,inf = 0x3fffffff;

int n,m,c,r,k,arr[mxn][mxn],dis[mxn],vis[mxn];
int prim(int now)
{
    fill(dis,dis+mxn,inf);
    fill(vis,vis+mxn,0);
    int ans = 0;dis[now] = 0;
    for(int i=1;i<=m;i++)
    {
        int index = -1 , mn = inf;
        for(int j=1;j<=m;j++)
        {
            if(!vis[j] && mn>dis[j])
            {
                mn = dis[j];
                index = j;
            }
        }
        if(index == -1) return -1;
        vis[index] = 1;
        ans += dis[index];
        for(int k=1;k<=m;k++)
            if(!vis[k] && dis[k]>arr[index][k])
                dis[k] = arr[index][k];
    }
    return ans;
}
int main()
{
    while(~sc(n,m))
    {
        if(!n) break;
        fill(arr[0], arr[0] + mxn * mxn, inf);
        for(int i=1;i<=n;i++)
        {
            sca(c,r,k);
            arr[c][r] = k;arr[r][c] = k;
        }
        prim(1)==-1?printf("?\n"):printf("%d\n",prim(1));
    }
    return 0;
}

 

 

Guess you like

Origin www.cnblogs.com/Shallow-dream/p/11788626.html