PAT甲級1030 Travel Plan (30 分)題解

在這裏插入圖片描述在這裏插入圖片描述
\quad這個題是一道最短路題,跟PAT甲級1003 Emergency (25 分)題解很像,即在求最短路的前提下,若有多條最短路,輸出花費最少的一條。PAT最愛考這種題,因爲花費最少滿足最優子結構,我們可以直接在Dijistra中進行更新。程序如下:

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

const int maxn = 501;
vector<pair<int, int> > E[maxn];
int vis[maxn], dis[maxn], path[maxn];
map<pair<int, int>, int> mp;  // 存放邊之間的權值
int c[maxn];  // 存放起點到終點的花費
void Dijistra(int s, int t)
{
	fill(dis, dis+maxn, 0x3f3f3f3f);
	dis[s] = 0;
    priority_queue<pair<int, int> > q;
    q.push({0, s});
    c[s] = 0;
    while(!q.empty())
    {
    	int u = q.top().second;
    	q.pop();
    	if(vis[u]==1) continue;
    	vis[u] = 1;
    	for (int i = 0; i < E[u].size(); ++i)
    	{
    		int v = E[u][i].first, w = E[u][i].second;
    		if(dis[v]>dis[u]+w)
    		{
    			path[v] = u;
    			dis[v] = dis[u]+w;
    			c[v] = c[u]+mp[{u, v}];
    			if(vis[v]==0) q.push({-dis[v], v});
    		}
    		else if(dis[v]==dis[u]+w && c[v]>mp[{u, v}]+c[u])
    		{
    			path[v] = u;
    			c[v] = mp[{u, v}]+c[u];
    			if(vis[v]==0) q.push({-dis[v], v});
    		}
    	}
    }
    vector<int> res;
    res.push_back(t);
    int temp = path[t];
    while(temp!=s)
    {
    	res.push_back(temp);
    	temp = path[temp];
    }
    res.push_back(s);
    for (int i = res.size()-1; i >= 0; --i)
    {
    	cout << res[i] << " ";
    }
    cout << dis[t] << " " << c[t];
}
int main(int argc, char const *argv[])
{
	int N, M, S, D;
	cin >> N >> M >> S >> D;
    while(M--)
    {
    	int u, v, w, cost;
    	cin >> u >> v >> w >> cost;
    	E[u].push_back({v, w});
    	E[v].push_back({u, w});
    	mp[{u, v}] = mp[{v, u}] = cost;
    }
    Dijistra(S, D);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章