ABC485E Colorful Route
记一个用 vector 删边的技巧。
无权最短路,考虑 bfs。
广搜好题,可以充分反映广搜解决“最小步数”问题的本质。
本题关键在于想到每条边只需要走一次。证明很简单,可以理解为“上上条边的选择不会影响当前决策“,再加上广搜是步数优先,所以最先到达 \(n\) 的就是最小的。
考虑怎么删边,考虑通过 \(c\) 边走到 \(u\),可以新开一个 vector 存下所有从 \(u\) 出发颜色为 \(c\) 的边,然后和 \(u\) 本身的 vector 做交换即可,这个交换是 \(O(1)\) 的,所以最终时间复杂度 \(O(m)\)。
#include<bits/stdc++.h>
//#include<atcoder/segtree>
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define mp make_pair
#define pii pair<int, int>
#define F(i,l,r) for(int i(l); i <= (r); ++ i)
#define G(i,r,l) for(int i(r); i >= (l); -- i)
//#define int ll
using namespace std;
//using namespace atcoder;
using ll = long long;
const int inf = 1e9;
const int N = 2.3e5;
const int mod = 1e9 + 7;
vector<pii> G[N];
struct D{
int u, s, c;
};
queue<D> q;
int n, m;
void Main(){
cin >> n >> m;
F(i, 1, m){
int u, v, w;
cin >> u >> v >> w;
G[u].pb(mp(v, w));
}
q.push(D{1, 0, 0});
while(q.size()){
D o = q.front();
q.pop();
int u = o.u, s = o.s, c = o.c;
if(u == n){
cout << s;
return ;
}
vector<pii> A;
for(pii o : G[u]){
int v = o.fi, w = o.se;
if(c == w){
A.pb(mp(v, w));
}
else{
q.push(D{v, s + 1, w});
}
}
swap(G[u], A);
}
cout << -1;
return ;
}
signed main(){
// freopen("test.out", "r", stdin);
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T;
T = 1;
// cin >> T;
while(T --) Main();
return fflush(0), 0;
}

浙公网安备 33010602011771号