欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

A1111 Online Map [dj+dfs]

程序员文章站 2022-06-11 18:03:25
...

**A1111 Online Map [dj+dfs]
思路:用两个Dijkstra。一个求最短路径(如果相同求时间最短的那条),一个求最快路径(如果相同求结点数最小的那条)
数组记录结点,dfs遍历输出结点

#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 501;
const int inf = 999999999;
int dis[501], Time[501], d[501][501], T[501][501], dispre[501], timepre[501], t1[501], nodenum[501];
bool visit[501];
int st, ed;
vector<int>shortpath, quickpath, temppath;
void dfs_shortpath(int v)
{
	shortpath.push_back(v);
	if (v == st) return;
	dfs_shortpath(dispre[v]);
}
void dfs_quickpath(int v)
{
	quickpath.push_back(v);
	if (v == st) return;
	dfs_quickpath(timepre[v]);
}
int main()
{
	fill(dis, dis + 501, inf);
	fill(Time, Time + 501, inf);
	fill(t1, t1 + 501, inf);
	fill(d[0], d[0] + 501 * 501, inf);
	fill(T[0], T[0] + 501 * 501, inf);
	int n, m;
	cin >> n >> m;
	int a, b, flag, len, t;
	for (int i = 0; i < m; i++)
	{
		cin >> a >> b >> flag >> len >> t;
		d[a][b] = len;
		T[a][b] = t;
		if (flag != 1)
		{
			d[b][a] = len;
			T[b][a] = t;
		}
	}
	cin >> st >> ed;
	dis[st] = 0;
	for (int i = 0; i < n; i++)
	{
		int u = -1, min = inf;
		for (int j = 0; j < n; j++)
		{
			if (visit[j] == false && dis[j] < min)
			{
				u = j;
				min = dis[j];
			}
		}
		if (u == -1) break;
		visit[u] = true;
		for (int v = 0; v < n; v++)
		{
			if (visit[v] == false)
			{
				if (d[u][v] + dis[u] < dis[v])
				{
					dis[v] = d[u][v] + dis[u];
					dispre[v] = u;
					t1[v] = T[u][v] + t1[u];
				}
				else if (d[u][v] + dis[u] == dis[v] && t1[v] > T[u][v] + t1[u])
				{
					dispre[v] = u;
					t1[v] = T[u][v] + t1[u];
				}
			}
		}
	}
	dfs_shortpath(ed);
	Time[st] = 0;
	fill(visit, visit + 501, false);
	for (int i = 0; i < n; i++)
	{
		int u = -1, min = inf;
		for (int j = 0; j < n; j++)
		{
			if (visit[j] == false && Time[j] < min)
			{
				u = j;
				min = Time[j];
			}
		}
		if (u == -1) break;
		visit[u] = true;
		for (int v = 0; v < n; v++)
		{
			if (visit[v] == false)
			{
				if (T[u][v] + Time[u] < Time[v])
				{
					Time[v] = T[u][v] + Time[u];
					timepre[v] = u;
					nodenum[v] = nodenum[u] + 1;
				}
				else if (Time[v] == T[u][v] + Time[u]&&nodenum[u]+1<nodenum[v])
				{
					timepre[v] = u;
					nodenum[v] = nodenum[u] + 1;
				}
			}
		}
	}
	dfs_quickpath(ed);
	printf("Distance = %d", dis[ed]);
	if (shortpath == quickpath) 
	{
		printf("; Time = %d: ", Time[ed]);
	}
	else {
		printf(": ");
		for (int i = shortpath.size() - 1; i >= 0; i--) {
			printf("%d", shortpath[i]);
			if (i != 0) printf(" -> ");
		}
		printf("\nTime = %d: ", Time[ed]);
	}
	for (int i = quickpath.size() - 1; i >= 0; i--) {
		printf("%d", quickpath[i]);
		if (i != 0) printf(" -> ");
	}
	return 0;

}