[AcWing 920] 最优乘车


按照换乘次数建图,求单源最短路
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N = 1e6 + 10;
const int INF = 0x3f3f3f3f;
int n, m;
int h[N], e[N], ne[N], w[N], idx;
int d[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++;
}
void dijkstra(int sp)
{
memset(d, 0x3f, sizeof d);
memset(st, false, sizeof st);
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, sp});
d[sp] = 0;
while (heap.size()) {
auto t = heap.top();
heap.pop();
auto v = t.second;
if (st[v])
continue;
st[v] = true;
for (int i = h[v]; i != -1; i = ne[i]) {
int j = e[i];
if (d[j] > d[v] + 1) {
d[j] = d[v] + 1;
heap.push({d[j], j});
}
}
}
}
void solve()
{
cin >> m >> n;
memset(h, -1, sizeof h);
string line;
// 换行
getline(cin, line);
for (int i = 0; i < m; i ++) {
getline(cin, line);
stringstream ssin(line);
vector<int> stop;
int p = 0;
while (ssin >> p)
stop.push_back(p);
for (int i = 0; i < stop.size(); i ++)
for (int j = i + 1; j < stop.size(); j ++)
add(stop[i], stop[j], 1);
}
dijkstra(1);
if (d[n] == INF)
cout << "NO" << endl;
else
cout << d[n] - 1 << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
return 0;
}
- 将与起点在同一线路的车站距离置为 \(1\),需要换成一次的车站距离置为 \(2\),\(\cdots\),求从起点到终点的最短路,最后把结果减 \(1\)(因为和起点在同一线路的实际不需要换乘)

浙公网安备 33010602011771号