图论-全源最短路径-对比Floyd算法与暴力Dijkstra算法

题目

输入顶点数N,有向边数M,接下来M行输入格式为u,v,w分别代表两个顶点u,v和两点之间边的权值w。输出全源最短路径
输入样例
6 8
0 1 1
0 3 4
0 4 4
1 3 2
2 5 1
3 2 2
3 4 3
4 5 3
输出样例
0 1 5 3 4 6
1073741823 0 4 2 5 5
1073741823 1073741823 0 1073741823 1073741823 1
1073741823 1073741823 2 0 3 3
1073741823 1073741823 1073741823 1073741823 0 3
1073741823 1073741823 1073741823 1073741823 1073741823 0

暴力Dijkstra算法代码

#include 
#include 
using namespace std;
const int maxn = 105;
const int inf = 0x3fffffff;
int N, M;//N个顶点,M条边
DWORD startTime, endTime;
struct Node{
	int v;
	int dist;
	Node(){}
	Node(int vv, int dd)
	{
		v = vv;
		dist = dd;
	}
};
vector<Node> G[maxn];//有向有权边 
bool vis[maxn];
int d[maxn];//存储最短距离 
void init()
{
	for(int i = 0; i < N; ++i)
	{
		vis[i] = false;
		d[i] = inf;
	}
}
//源点s 
void Dijkstra(int s)
{
	init();
	d[s] = 0;
	for(int i = 0; i < N; ++i)
	{
		int u, udist, mindist = inf;
		for(int j = 0; j < N; ++j)//寻找d[]最小值 
		{
			if(!vis[j] && d[j] < mindist)
			{
				u = j;
				udist = mindist = d[j];
			}
		}
		vis[u] = true;
		for(int k = 0; k < G[u].size(); k++)
		{
			int v = G[u][k].v;
			int vdist = G[u][k].dist;
			if(!vis[v] && udist + vdist < d[v])
			{
				d[v] = udist + vdist;
			}
		}
	} 
}
int main(int argc, char *argv[]) {
	scanf("%d%d", &N, &M);
	for(int i = 0; i < M; ++i)
	{
		int u, v, w;//边uv,点u与点v之间的边,权值为w
		scanf("%d%d%d", &u, &v, &w);
		Node node = Node(v, w);
		G[u].push_back(node);
	}
	startTime = GetTickCount();
	for(int i = 0; i < N; ++i)
	{
		Dijkstra(i);
		for(int i = 0; i < N; ++i)
			printf("%d ", d[i]);
		printf("\n");
	}
	endTime = GetTickCount();
	cout << endTime - startTime << "ms" << endl;
	return 0;
}

暴力Dijkstra算法速度

图论-全源最短路径-对比Floyd算法与暴力Dijkstra算法_第1张图片

Floyd算法代码

#include 
#include 
using namespace std;
const int maxn = 105;
const int inf = 0x3fffffff;
int N, M;//N个顶点,M条边
DWORD startTime, endTime;
struct Node{
	int v;
	int dist;
	Node(){}
	Node(int vv, int dd)
	{
		v = vv;
		dist = dd;
	}
};
vector<Node> G[maxn];//有向有权边 
int d[maxn][maxn];//存储最短距离 
//源点s 
void Floyd()
{
	for(int k = 0; k < N; ++k)
	{
		for(int i = 0; i < N; ++i)
		{
			for(int j = 0; j < N; ++j)
			{
				if(d[i][k] != inf && d[k][j] != inf && d[i][k] + d[k][j] < d[i][j])
				{
					d[i][j] = d[i][k] + d[k][j];
				}
			}
		}
	}
}
int main(int argc, char *argv[]) {
	scanf("%d%d", &N, &M);
	for(int i = 0; i < N; ++i)
	{
		for(int j = 0; j  < N; ++j)
		{
			d[i][j] = inf;
		}
	}
	for(int i = 0; i < N; i++)
	{
		d[i][i] = 0;//顶点i到顶点i的距离是0 
	}
	for(int i = 0; i < M; ++i)
	{
		int u, v, w;
		scanf("%d%d%d", &u, &v, &w);
		d[u][v] = w;
	}
	
	startTime = GetTickCount();
	Floyd();
	for(int i = 0; i < N; ++i)
	{
		for(int j = 0; j < N; ++j)
		{
			printf("%d ", d[i][j]);
		}
		printf("\n");
	}
	endTime = GetTickCount();
	cout << endTime - startTime << "ms" << endl;
	return 0;
}

Floyd算法速度

图论-全源最短路径-对比Floyd算法与暴力Dijkstra算法_第2张图片

你可能感兴趣的:(算法笔记)