c语言贪心算法最小生成树,贪心算法——最小生成树

/*主题:贪心算法之最小生成树(Kruskal算法)

* 作者:chinazhangjie

* 邮箱:[email protected]

* 开发语言:C++

* 开发环境:Visual Studio 2005

* 时间:2010.12.01*/#include#include#include#includeusingnamespacestd ;structTreeNode

{public:

TreeNode (intnVertexIndexA=0,intnVertexIndexB=0,intnWeight=0)

: m_nVertexIndexA (nVertexIndexA),

m_nVertexIndexB (nVertexIndexB),

m_nWeight (nWeight)

{ }

friendbooloperator

{returnlth.m_nWeight>rth.m_nWeight ;

}public:intm_nVertexIndexA ;intm_nVertexIndexB ;intm_nWeight ;

} ;//并查集classUnionSet

{public:

UnionSet (intnSetEleCount)

: m_nSetEleCount (nSetEleCount)

{

__init() ;

}//合并i,j。如果i,j同在集合中,返回false。否则返回trueboolUnion (inti,intj)

{intifather=__find (i) ;intjfather=__find (j) ;if(ifather==jfather )

{returnfalse;//copy (m_nvFather.begin(), m_nvFather.end(), ostream_iterator (cout, " "));//cout << endl ;}else{

m_nvFather[jfather]=ifather ;//copy (m_nvFather.begin(), m_nvFather.end(), ostream_iterator (cout, " "));//cout << endl ;returntrue;

}

}private://初始化并查集int__init()

{

m_nvFather.resize (m_nSetEleCount) ;for(vector::size_type i=0;

i

{

m_nvFather[i]=static_cast(i) ;//cout << m_nvFather[i] << " " ;}//cout << endl ;return0;

}//查找index元素的父亲节点 并且压缩路径长度int__find (intnIndex)

{if(nIndex==m_nvFather[nIndex])

{returnnIndex;

}returnm_nvFather[nIndex]=__find (m_nvFather[nIndex]);

}private:

vectorm_nvFather ;//父亲数组vector::size_type m_nSetEleCount ;//集合中结点个数} ;classMST_Kruskal

{

typedef priority_queueMinHeap ;public:

MST_Kruskal (constvector>&graph)

{

m_nNodeCount=static_cast(graph.size ()) ;

__getMinHeap (graph) ;

}voidDoKruskal ()

{

UnionSet us (m_nNodeCount) ;intk=0;while(m_minheap.size()!=0&&k

{

TreeNode tn=m_minheap.top () ;

m_minheap.pop () ;//判断合理性if(us.Union (tn.m_nVertexIndexA, tn.m_nVertexIndexB))

{

m_tnMSTree.push_back (tn) ;++k ;

}

}//输出结果for(size_t i=0; i

{

cout<"<

}

}private:void__getMinHeap (constvector>&graph)

{for(inti=0; i

{for(intj=0; j

{if(graph[i][j]!=numeric_limits::max())

{

m_minheap.push (TreeNode(i, j, graph[i][j])) ;

}

}

}

}private:

vectorm_tnMSTree ;intm_nNodeCount ;

MinHeap m_minheap ;

} ;intmain ()

{constintcnNodeCount=6;

vector>graph (cnNodeCount) ;for(size_t i=0; i

{

graph[i].resize (cnNodeCount, numeric_limits::max()) ;

}

graph[0][1]=6;

graph[0][2]=1;

graph[0][3]=3;

graph[1][2]=5;

graph[1][4]=3;

graph[2][3]=5;

graph[2][4]=6;

graph[2][5]=4;

graph[3][5]=2;

graph[4][5]=6;

graph[1][0]=6;

graph[2][0]=1;

graph[3][0]=3;

graph[2][1]=5;

graph[4][1]=3;

graph[3][2]=5;

graph[4][2]=6;

graph[5][2]=4;

graph[5][3]=2;

graph[5][4]=6;

MST_Kruskal mst (graph);

mst.DoKruskal () ;

}

你可能感兴趣的:(c语言贪心算法最小生成树)