图的概念

连通图:无向图中每一对顶点间都存在一条路径

强连通图:有向图中每一对顶点间都存在一条路径

弱连通图:有向图去掉边的方向后可以变成连通图

完全图:每一对顶点间都存在一条边

邻接矩阵:用一个二维数组來表示图

邻接表:用一个数组存储图的结点,每个结点保存一个链表,链表中存放所有邻接的顶点

拓扑排序:对有向无圈图的一种排序,它使得如果存在一条vi到vj的路径,那么在排序中vj出现在vi的后面。

排序过程:
用一个队列存储入度为0的顶点
1.遍历图,将入度为0的顶点保存到队列中
2.从队列中取出一个顶点,更新该顶点的邻接顶点的入度(减1),如果入度为0,则保存到队列中。
3.循环执行步骤2,直至队列为空。
单源最短路径:

Dijkstra算法:贪心算法

最小生成树(无向图):

Prim算法:贪心算法,选择具有最小权值的边

Kruskal算法

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

struct Edge
{
	int from, to, weight;
	Edge(int f, int t, int w) : from(f), to(t), weight(w) {}
	bool operator >(const Edge& e)const{return weight > e.weight;}
	bool operator <(const Edge& e)const{return weight < e.weight;}
};

bool addEdge(vector<int>& V, const Edge& e);  // use union/find(quick find)

int main()
{
	vector<Edge> E;
	int from, to, w;
	int n;  // number of vertex
	cin>>n;
	vector<int> V(n);   // vertex union
	for (int i=0; i<n; ++i)
	{
		V[i] = i;
	}
	
	while(cin>>from>>to>>w)
		E.push_back(Edge(from, to, w));
	make_heap(E.begin(), E.end(), greater<Edge>());
	int count = 0;  // number of edge added
	while(!E.empty())
	{
		Edge e = E[0];
		if(addEdge(V, e))  
		{
			++count;
			cout<<e.from<<"->"<<e.to<<": "<<e.weight<<endl;
			if(count==n-1) break;   // succeed.
		}
		pop_heap(E.begin(), E.end(), greater<Edge>());
		E.pop_back();
	}
	if(count != n-1)
		cout<<"failed."<<endl;
	return 0;
}

bool addEdge(vector<int>& V, const Edge& e)
{
	// find the root
	int i = V[e.from];  
	int j = V[e.to];
	if(i==j) 
		return false;
	// union: replace i with j
	int temp = V[j];
	for (int k=0; k<V.size(); ++k)
	{
		if (V[k]==i)
		{
			V[k] = j;
		}
	}
	return true;
}


posted @ 2012-09-25 20:18  刘军newhand_liu  阅读(218)  评论(0编辑  收藏  举报