L2-001 紧急救援 - Dijkstra堆优化最短路
PTA - L2 - 001 紧急救援
邻接表建图(稀疏图)
// 将结点b增加到结点a后
int h[N], w[N], e[N], ne[N], idx;
void add(int a, int b, int c)
{
w[idx] = c, e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
STL建图(稠密图、稀疏图)
// 重载小于号是为了便于dijsktra中大根堆的建立
struct edge
{
int x, w; // x 是结点编号,w是权值
bool operator<(const node& u)const {
return w == u.w ? x < u.x : w > u.w; }
};
vector<edge> g[N];
思路:
本题不仅要求最短路,同时需要维护最短路上的救援队的最大数量、最短路的数量和最短路的路径。
- 出现最最短路的情况 dist[j] > dist[i] + w
- 更新最短路的路径
- 跟新救援队的数量
- 出现重复的路径 dist[j] == dist[i] + w
- 查找当前救援队的数量是否最大,若不是,则需要更新,更新后,最短路的路径也要更新。
- 同时,出现重复路径时,最短路径的数量 ++ 。
最后需要注意由于记录最短路的数组pre是记录前驱结点,最后输出时要倒序输出。
1. 邻接表建图
#include <bits/stdc++.h>
#define pii pair<int, int>
using namespace std;
const int N = 510;
int n, m, start, endd;
int h[N * N], e[N * N], ne[N * N], w[N * N], idx;
int dist[N];
int cnt[N], team[N], sum_team[N], pre[N];
bool st[N];
void insert(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx]