2019独角兽企业重金招聘Python工程师标准>>>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <initializer_list>
#include <memory>
template<typename T>
class Graph{private:std::map<T, map<T, unsigned int>> graph; //存储无向图. std::map<T, std::vector<T>> edge; //邻接链表. 也就是说给定一个结点另外有多少个结点是与其相连接的. std::queue<T> vertex; //存储所有的结点. std::set<T> memberFromQueue; //从栈内弹出的元素放到set中.std::vector<T> currentVertex;unsigned int vertexNumber;public:template<typename Ty, unsigned int N>Graph(const Ty (&edges)[N][3]);~Graph();void primAlgorithm();
};
template<typename T>
template<typename Ty, unsigned int N>
Graph<T>::Graph(const Ty (&edges)[N][3]):vertex(nullptr),vertexNumber(vertexs.size())
{if(vertexs.size() == 0){throw std::bad_cast();}std::cout<<"enter successfully"<<std::endl;for(int i=0; i<N; ++i){this->graph[edges[i][0]][edges[i][2]] = edges[i][1]; //map的特性就是如果其中不含有edges[i][0]以及edge[i][0]元素就会自动创建一个. this->graph[edges[i][2]][edges[i][0]] = edges[i][1];this->edge[edges[i][0]].push_back(edges[i][2]); //与结点edges[i][0]相接的所有结点,被放到与其对应的vector中. this->edge[edges[i][2]].push_back(edges[i][0]); //同上. }for(std::map<Ty, std::map<Ty, unsigned int>>::const_iterator it = this->edge.cbegin(); it != this->edge.cend(); ++it){ //把所有结点都放到vertex中. this->vertex.push(it->first);}std::cout<<"out"<<std::endl;
}
template<typename T>
void Graph<T>::primAlgorithm()
{T head;int total = 0;head = this->vertex.front(); //弹出栈内第一个元素. this->vertex.pop(); //删除该元素.this->memberFromQueue.insert(head);this->currentVertex.push_back(head);while( !this->vertex.empty() ){ //当给定的无向图不为空. int i=0;int j=0;int min=0;int flag =0;T start;T end;for(i=0; i<this->currentVertex.size(); ++i){ //当前顶点. for(j=0; i<this->edge[this->currentVertex[i]].size(); ++j){ //与当前顶点(head)相连接的有多少个顶点, 逐个访问这些与当前顶点相连接的结点. if(this->memberFromQueue.find(this->edge[this->currentVertex[i]][j]) == this->memberFromQueue.end()){ //查找当前顶点时候存在memberFromQueue中. if(flag == 0){ //如果给定的顶点是树中的第一个. 那么令min等于当前顶点与任意一边的加权值. min = this->graph[this->currentVertex[i]][this->edge[this->currentVertex[i]][j]]; //获得的是currentVertex[i] 和 edge[currentVertex[i]] [j] 这两个结点的加权值.flag = 1; }if(this->graph[this->currentVertex[i]][this->edge[this->currentVertex[i]][j]] <= min){min = this->graph[this->currentVertex[i][this->edge[this->currentVertex[i]][j]];start = this->currentVertex[i];end = this->edge[this->currentVertex[i]][j];}}}}std::cout<<start<<"----"<<min<<"-----"<<end<<std::endl;//输出边以及加权值.this->vertex.pop(); //删除栈内当前的顶点元素.this->memberFromQueue.insert(end);this->currentVertex.push_back(end); }}