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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值