https://ac.nowcoder.com/acm/contest/52244
F 坐火车
大意:在经过最少城市的条件下1到n的最短路
思路:bfs预处理出经过最少城市的路线(权值为1),按途经城市最少的路线跑dijkstra(d[j] != d[num] + 1,即不是最少城市路线,continue)
//坐火车
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <sstream>
#include <cstring>
#include <numeric>
#include <istream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <queue>
#include <map>
#include <stack>
#include <set>
using namespace std;
const int inf = 0x3f3f3f3f, mod = 1e9 + 7;
const int N = 1e5 + 10, M = 4 * N; //题目中N是1e5,M是2e5,双向边
#define LL long long
#define PII pair<int, int>
int n, m, d[N], ne[M], e[M], h[N], idx, w[M], vis[N], dis[N], st[N];
void add(int a, int b, int c){
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++;
}
void bfs(){
queue<int> q;
q.push(1);
vis[1] = 1;
d[1] = 1;
while(q.size()){
int t = q.front();
q.pop();
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
if(!vis[j]){
d[j] = d[t] + 1;
vis[j] = 1;
q.push(j);
}
}
}
}
int dijkstra(){
memset(dis, inf, sizeof dis);
dis[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
while(heap.size()){
auto t = heap.top();
heap.pop();
int num = t.second, dist = t.first;
if(st[num]) continue;
st[num] = 1;
for(int i = h[num]; i != -1; i = ne[i]){
int j = e[i];
if(d[j] != d[num] + 1) continue;
if(dis[j] > dis[num] + w[i]){
dis[j] = dis[num] + w[i];
heap.push({dis[j], j});
}
}
}
return dis[n];
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(), cout.tie();
memset(h, -1, sizeof h);
cin >> n >> m;
while(m --){
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
bfs();
int ans = dijkstra();
cout << d[n] << ' ' << ans;
return 0;
}