Dijkstra-------多标尺(DFS实现)

#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXN = 510;
const int INF = 100000000;
struct node {
	int x;
	int d;
	node() {}
	node(int a, int b) {
		x = a;
		d = b;
	}
	bool operator < (const node& a)const
	{
		if (d == a.d) return x < a.x;
		else return d > a.d;
	}
};
int cost[MAXN][MAXN];//储存两个结点之间的边权(也就是这里所说的花费)
int c[MAXN];//记录到这个结点的最小花费
vector<node> Adj[MAXN];//储存两个结点的距离
vector<int>  pre[MAXN];//储存路线
vector<int> tempPath;//临时路径
vector<int> path;//最优路径
int n, m, s;
int st;//起始结点的位置
int ed;//终点结点的位置
int dis[MAXN];//储存到这个结点的最短距离
int minCost = INF;//记录最消耗的值
void Dijkstra(int s)
{
	fill(dis, dis + n, INF);
	dis[s] = 0;
	priority_queue<node> q;
	q.push(node(s, dis[s]));
	while (!q.empty())
	{
		node x = q.top();
		q.pop();
		for (int i = 0; i < Adj[x.x].size(); i++)
		{
			node y = Adj[x.x][i];
			if (dis[y.x] > x.d + y.d)
			{
				dis[y.x] = x.d + y.d;
				pre[y.x].clear();
				pre[y.x].push_back(x.x);
				q.push(node(y.x, dis[y.x]));
			}
			else if (dis[y.x] == x.d + y.d)
			{
				pre[y.x].push_back(x.x);
			}
		}

	}
}
void DFS(int v)
{
	if (v == st)//如果到了递归边界,也就是到了起始位置
	{
		tempPath.push_back(v);
		int tempCost = 0;
		for (int i = tempPath.size() - 1; i > 0; i--)//循环,用来计算出临时路线的花费
		{
			int id = tempPath[i];
			int idNext = tempPath[i - 1];
			tempCost += cost[id][idNext];
		}
		if (tempCost < minCost)//如果花费小于最小花费的话
		{
			minCost = tempCost;
			path = tempPath;//将临时路径复制给最佳路径
		}
		tempPath.pop_back();
		return;
	}
	tempPath.push_back(v);
	for (int i = 0; i < pre[v].size(); i++)
	{
		DFS(pre[v][i]);
	}
	tempPath.pop_back();
}
int main()
{
	cin >> n >> m >> st >> ed;
	int u, v, w;
	fill(cost[0], cost[0] + MAXN * MAXN, INF);
	for (int i = 0; i < m; i++)
	{
		cin >> u >> v >> w;
		cin >> cost[u][v];
		Adj[u].push_back(node(v, w));
		Adj[v].push_back(node(u, w));//因为是无向图
		cost[v][u] = cost[u][v];
	}
	Dijkstra(st);
	DFS(ed);
	for (int i = path.size() - 1; i >= 0; i--)
	{
		cout << path[i] << " ";
	}
	cout << dis[ed] << " " << minCost;
	system("pause");
	return 0;
}
/*
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
*/

猜你喜欢

转载自blog.csdn.net/scwmason/article/details/80972343