数据结构实验之图论六:村村通公路

来源:互联网 发布:fastdfs nginx 缩略图 编辑:程序博客网 时间:2024/05/16 15:48

Problem Description

当前农村公路建设正如火如荼的展开,某乡镇政府决定实现村村通公路,工程师现有各个村落之间的原始道路统计数据表,表中列出了各村之间可以建设公路的若干条道路的成本,你的任务是根据给出的数据表,求使得每个村都有公路连通所需要的最低成本。

Input

连续多组数据输入,每组数据包括村落数目N(N <= 1000)和可供选择的道路数目M(M <= 3000),随后M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个村庄的编号和修建该道路的预算成本,村庄从1~N编号。 

Output

输出使每个村庄都有公路连通所需要的最低成本,如果输入数据不能使所有村庄畅通,则输出-1,表示有些村庄之间没有路连通。 

Example Input

5 81 2 121 3 91 4 111 5 32 3 62 4 93 4 44 5 6

Example Output

19

代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INF 0x3f3f3f3f
using namespace std;
int map[1001][1001], v[1001];
int flag;
struct node
{
    int data, step;
};
struct node p[1001];

void bfs(int n)
{
    int i, sum=0;
    int d[1001];
    v[1]=1;
    for(i=1; i<=n; i++)
    {
        d[i]=map[1][i];
    }
    int pos, k=1;
    for(int j=1; j<n; j++)
    {
        int mm=INF;
        for(i=1; i<=n; i++)
        {
            if(v[i]!=1&&d[i]<mm)
            {
                mm=d[i];
                pos=i;
            }
        }
        if(mm==INF)
        {
            k=0;
            break;
        }
        sum=sum+mm;
        v[pos]=1;
        for(i=1; i<=n; i++)
        {
            if(v[i]!=1&&d[i]>map[pos][i])
            {
                d[i]=map[pos][i];
            }
        }
    }
    if(k)
        printf("%d\n", sum);
    else
        printf("-1\n");
}

int main()
{
    int m, a, b, n, i, j, c;
    while(~scanf("%d", &n))
    {
        scanf("%d", &m);
        memset(map, INF, sizeof(map));
        memset(v, 0, sizeof(v));
        for(i=1; i<=n; i++)
        {
            for(j=1; j<=n; j++)
            {
                if(i==j)
                    map[i][j]=0;
            }
        }
        while(m--)
        {
            scanf("%d %d %d", &a, &b, &c);
            if(map[a][b]>c)
            map[a][b]=map[b][a]=c;
        }
        bfs(n);
    }
    return 0;
}


阅读全文
0 0