文章

34

粉丝

0

获赞

142

访问

4.5k

头像
最短路径问题 优先队列做会简单一点题解:
P1344 浙江大学机试题
发布于2026年3月7日 22:23
阅读数 81

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e3 + 3;
int dis[N]; bool visited[N]; int cost[N]; //注意本题有两个约束条件,但是最主要的还是最短路
struct Node{
	int u, d, p;
	bool operator < (const Node &other) const{
		if(d == other.d) return p > other.p;
		else return d > other.d;   //优先队列会帮助自动排序,最短路的时候头一个代价就是最小的
	}
};
vector<Node> g[N];

void dijkstra()
{
	int start, end; cin >> start >> end;
	priority_queue<Node> pq; //
	dis[start] = 0; cost[start] = 0;
	pq.push({start, 0, 0});
	while(pq.size())
	{
		auto N = pq.top(); pq.pop();
		int u = N.u, d = N.d, p = N.p;
		visited[u] = true;
		if(visited[end]) break;
		for(const auto NN : g[u])
		{
			int n_u = NN.u, n_d = NN.d, n_p = NN.p;
			if(!visited[n_u] && dis[n_u] > dis[u] + n_d){
				dis[n_u] = dis[u] + n_d;
				cost[n_u] = cost[u] + n_p;
				pq.push({n_u, dis[n_u], cost[n_u]});
			}
		}
	}
	
	cout << dis[end] << ' ...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发