xmuOJ 1500 最小生成树

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了xmuOJ 1500 最小生成树脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

这是一道原始的最小生成树问题。
http://acm.xmu.edu.cn/JudgeOnline/problem.php?cid=1023&pid=3

代码可以看做是模板代码:

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
 
using namespace std;
 
int  lingjie[101][101]; //邻接矩阵
int  dist[1001];//
int parent[1001];//
 
int main(){
 
    int N; //顶点个数
    vector<int> MIT; //最小生成树,存储顶点序号
    vector<int> LEFT;//剩余的点
    int length = 0; //最小生成树
    while (scanf("%d",&N),N!=0)
    {
        MIT.clear();
        LEFT.clear();
        length = 0;
 
        //初始化lingjie[][]
        for (int i = 1; i <=  N; i++)
        {
            for (int j = 1; j <=  N; j++)
            {
                lingjie[i][j] = INT_MAX;
            }
        }
 
        //序号从1开始
        int x, y, d,i,j;
        for ( i = 1; i <= N*(N - 1)/2 ; i++)
        {
            scanf("%d %d %d", &x, &y, &d);
            lingjie[x][y] = lingjie[y][x] = d;
        }
        for ( i = 1; i <= N; i++)
        {
            LEFT.insert(LEFT.end(), i);
        }
        int v = *LEFT.begin();
        MIT.insert(MIT.end(), v);
        LEFT.erase(LEFT.begin());
 
        //初始化dist[][] , parent[]
        for (i = 1; i <= N; i++)
        {
            dist[i] = lingjie[i][v];
            parent[i] = v; //全部先设为v
        }
 
        //主循环
        while (LEFT.size() != 0){
            d = dist[*LEFT.begin()];
            vector<int>::iterator mark = LEFT.begin();
            for (vector<int>::iterator i = LEFT.begin() + 1; i != LEFT.end(); i++)//寻找到MIT最近的点
            {
                if (d > dist[*i])
                {
                    d = dist[*i];
                    mark = i;
                }
            }
            v = *mark;
            MIT.insert(MIT.end(),*mark);
            LEFT.erase(mark);
             
            length += d;
            //更新dist[]
            for (vector<int>::iterator j = LEFT.begin(); j != LEFT.end(); j++)//更新当前剩余点到MIT的dist
            {
                if (lingjie[*j][v] < dist[*j])
                {
                    dist[*j] = lingjie[*j][v];
                    parent[*j] = v;  //预处理时: lingjie[i][i] = MAX ,否则parent[i] =i 恒成立
                }
            }
 
        }
        //end of 主循环
         
        PRintf("%dn", length);
    }
    return 0;
}
 
/*
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
*/
/**************************************************************
    Problem: 1500
    User: cld378632668
    Language: C++
    Result: Accepted
    Time:3 ms
    Memory:1560 kb
****************************************************************/

脚本宝典总结

以上是脚本宝典为你收集整理的xmuOJ 1500 最小生成树全部内容,希望文章能够帮你解决xmuOJ 1500 最小生成树所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。