08-图7 公路村村通 (30 分)

 

 

08-图7 公路村村通 (30 分)

现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。

输入格式:

输入数据包括城镇数目正整数N(1000)和候选道路数目M(3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。

输出格式:

输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出1,表示需要建设更多公路。

输入样例:

6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3

输出样例:

12

 

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Xml;


class P
{ 

    class T
    {
        static bool 没有全部加入(bool[] check)
        {
            foreach (var item in check)
            {
                if (item == false)
                    return true;
            }
            return false;
        }
        static void Main(string[] args)
        {
            var firstLine = Console.ReadLine().Split(' ');

            var V = int.Parse(firstLine[0]);
            var E = int.Parse(firstLine[1]);

            int[][] data = new int[V][];

            for (int i = 0; i < V; i++)
            {
                data[i] = new int[V];
                for (int j = 0; j < V; j++)
                {
                    data[i][j] = int.MaxValue;
                }
            }
            for (int i = 0; i < E; i++)
            {
                var tempLine = Console.ReadLine().Split(' ');
                int j = 0;
                var a1 = int.Parse(tempLine[j++]) - 1;
                var a2 = int.Parse(tempLine[j++]) - 1;
                var a3 = int.Parse(tempLine[j++]);
                data[a2][a1] = data[a1][a2] = a3;

            }


            bool[] check = new bool[V];
            check[0] = true;

            int sum = 0;
            while (没有全部加入(check))
            {
                int min = int.MaxValue;
                int tempV = -1;
                for (int i = 0; i < V; i++)
                {
                    if (check[i] == true)
                    {


                        for (int j = 0; j < V; j++)
                        {
                            if (check[j] == false)
                            {
                                if (min > data[i][j])
                                {
                                    min = data[i][j];
                                    tempV = j;

                                }
                            }

                        }


                    }
                }
                if (tempV == -1)
                {
                    Console.WriteLine(-1);//说明并不联通,  加入列表的和没加入列表的,两点之间路径不存在.
                    return;
                }
                check[tempV] = true;
                sum += min;
            }
            Console.WriteLine(sum);
            return;


             



        } 
    }

}

 

posted @ 2018-10-29 16:58  interim  阅读(233)  评论(0编辑  收藏  举报