HDU 2544 最短路

传送门

最短路,没有任何变形,还是中文题。

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

const int INF = 1e9;
const int MAXN = 105;
int N, M;
int g[MAXN][MAXN];
int dis[MAXN];
bool vis[MAXN];

void dijkstra(int s)
{
	dis[s] = 0;
	for (int i = 0; i < N; i++)
	{
		int u = -1, mind = INF;
		for (int j = 1; j <= N; j++)
		{
			if (!vis[j] && dis[j] < mind)
			{
				mind = dis[j];
				u = j;
			}
		}
		vis[u] = 1;
		for (int j = 1; j <= N; j++)
		{
			if (!vis[j] && g[u][j] != -1)
			{
				if (dis[u] + g[u][j] < dis[j])
				{
					dis[j] = dis[u] + g[u][j];
				}
			}
		}
	}
}

int main()
{
	int a, b, c;
	for (; ~scanf("%d%d", &N, &M);)
	{
		if (!N && !M) break;
		memset(g, -1, sizeof g);
		memset(vis, 0, sizeof vis);
		fill(dis + 1, dis + N + 1, INF);           //
		for (; M--;)
		{
			scanf("%d%d%d", &a, &b, &c);
			if (g[a][b] == -1) g[a][b] = g[b][a] = c;
			else g[a][b] = g[b][a] = min(g[a][b], c);                // 邻接矩阵处理重边
		}
		dijkstra(1);
		printf("%d\n", dis[N]);
	}

    return 0;
}

4月8日更新。优先队列优化的dijkstra版本:(上面那个15ms,这个0ms。。)

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <utility>
#include <queue>
using namespace std;

const int INF = 1e9;
const int MAXN = 105;
int N, M;

int g[MAXN][MAXN];
int d[MAXN];
bool vis[MAXN];

struct Node
{
	int n, d;
	bool operator<(const Node& n0) const
	{
		return d > n0.d;
	}
};

void init()
{
	memset(g, -1, sizeof g);
	memset(vis, 0, sizeof vis);
	fill(d + 1, d + N + 1, INF);
}

void dijkstra(int s)
{
	priority_queue<Node> q;
	d[s] = 0;
	q.push(Node{ s,d[s] });

	for (; !q.empty();)
	{
		Node u = q.top();
		q.pop();
		if (vis[u.n]) continue;

		vis[u.n] = true;
		for (int j = 1; j <= N; j++)
		{
			if (!vis[j] && g[u.n][j] != -1)
			{
				if (d[u.n] + g[u.n][j] < d[j])
				{
					d[j] = d[u.n] + g[u.n][j];
					q.push(Node{ j,d[j] });
				}
			}
		}
	}
}

int main()
{
	int a, b, c;
	for (; ~scanf("%d%d", &N, &M);)
	{
		if (!N && !M) break;
		init();
		for (; M--;)
		{
			scanf("%d%d%d", &a, &b, &c);
			if (g[a][b] == -1) g[a][b] = g[b][a] = c;
			else g[a][b] = g[b][a] = min(g[a][b], c);                // 邻接矩阵处理重边
		}
		dijkstra(1);
		printf("%d\n", d[N]);
	}

	return 0;
}

posted @ 2019-03-23 13:47  CrossingOver  阅读(95)  评论(0编辑  收藏  举报