• [置顶] 最小生成树Prim算法


    二话不说直接贴代码

    原图传送门:http://www.tyut.edu.cn/kecheng1/site01/suanfayanshi/minispantree.asp

    但是上面展现的是克鲁斯卡尔算法。我这里是普里姆算法。

    #include <iostream>
    #include <list>
    #include <deque>
    #include <algorithm>
    using namespace std;
    
    typedef struct Line
    {
    	int Dot1;
    	int Dot2;
    	int Power;
    }Line;
    
    static const int arr[] = {0,1,6,
    	0,2,1,
    	0,3,5,
    	1,2,5,
    	1,4,3,
    	2,3,7,
    	2,4,5,
    	2,5,4,
    	3,5,2,
    	4,5,6
    };
    
    
    void BuildMap(list<Line>& vet)
    {
    	/*do
    	{
    	Line temp;
    	cin>>temp.Dot1>>temp.Dot2>>temp.Power;
    	vet.push_back(temp);
    	}while(getchar() != '#');*/
    	for(int i = 0;i < sizeof(arr)/(sizeof(int)*3);++i)
    	{
    		Line temp;
    		temp.Dot1 = arr[i*3];
    		temp.Dot2 = arr[i*3+1];
    		temp.Power = arr[i*3+2];
    		vet.push_back(temp);
    	}
    }
    
    void MST(list<Line>&map,list<Line>& tree)
    {
    	list<Line *> Open;
    	list<int>	OpenId;
    	for(auto p = map.begin();p != map.end();++p)
    	{
    		Open.push_back(&*p);
    		if(find(OpenId.begin(),OpenId.end(),p->Dot1) == OpenId.end())
    			OpenId.push_back(p->Dot1);
    		if(find(OpenId.begin(),OpenId.end(),p->Dot2) == OpenId.end())
    			OpenId.push_back(p->Dot2);
    	}
    	Open.sort([](const Line* a,const Line* b){return a->Power < b->Power;});//支持C++11的编译器
    	tree.push_back(**Open.begin());
    	OpenId.erase(find(OpenId.begin(),OpenId.end(),(*Open.begin())->Dot1));
    	OpenId.erase(find(OpenId.begin(),OpenId.end(),(*Open.begin())->Dot2));
    	Open.pop_front();
    	auto q = Open.begin();
    	while(!OpenId.empty())
    	{
    		if(find(OpenId.begin(),OpenId.end(),(*q)->Dot1) == OpenId.end()
    			&& find(OpenId.begin(),OpenId.end(),(*q)->Dot2) == OpenId.end())
    		{//已加入
    			Open.erase(q);
    			q = Open.begin();
    		}
    		else if(find(OpenId.begin(),OpenId.end(),(*q)->Dot1) == OpenId.end()
    			|| find(OpenId.begin(),OpenId.end(),(*q)->Dot2) == OpenId.end())
    		{//已加入
    			if(find(OpenId.begin(),OpenId.end(),(*q)->Dot1) == OpenId.end())
    				OpenId.erase(find(OpenId.begin(),OpenId.end(),(*q)->Dot2));
    			else if(find(OpenId.begin(),OpenId.end(),(*q)->Dot2) == OpenId.end())
    				OpenId.erase(find(OpenId.begin(),OpenId.end(),(*q)->Dot1));
    			tree.push_back(**q);
    			Open.erase(q);
    			q = Open.begin();
    		}
    		else
    		{
    			++q;
    		}
    	}
    }
    
    
    int main()
    {
    	list<Line> map;
    	list<Line> tree;
    	BuildMap(map);
    	MST(map,tree);
    	return 0;
    }


  • 相关阅读:
    整合SSH遇到的问题
    学习动态代理实现业务层的事务控制遇到的问题
    docker局域网独立IP外网访问配置
    第23次CSP-D题解法
    Nordic Bluetooth 切换到DFU Mode
    MySQL事务、锁和MVCC
    深拷贝和浅拷贝的区别是什么?
    python是如何进行内存管理的
    数据库的事务
    斐波那契数列
  • 原文地址:https://www.cnblogs.com/pangblog/p/3367624.html
Copyright © 2020-2023  润新知