AT_arc061_e题解
AT_arc061_e
题面
Snuke 的城镇有地铁行驶,地铁线路图包括
第
如果乘客只乘坐同一公司的铁路,他只需要花费一元,但如果更换其他公司的铁路需要再花一元。当然,如果你要再换回原来的公司,你还是要花一元。
Snuke 在 -1。
思路
考虑对每条线路建立一个虚点,如下图所示(以样例
可以发现一个公司统属的线路连接的所有站点之间可以任意通行而只产生
这样操作之后就可以实现同一个公司连接的一个联通块内的所有站点可以任意通行而只产生
为了帮助理解,下面给出更一般的情况:
建完图以后,就可以对图跑一遍正常的最短路。需要注意的是,为了避免计算边权时出现浮点数,可以通过把上图的所有
代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
const int N = 2e6+10;
struct node {int to, w, c;};
bool cmp(node x, node y) {return x.c < y.c;}
vector<node> g[N];
int n, m;
int dist[N];
bitset<N> st;
inline void dij() {
priority_queue<pii, vector<pii>, greater<pii>> hp;
memset(dist, 0x3f, sizeof dist);
hp.push({0, 1});
dist[1] = 0;
while(!hp.empty()) {
int u = hp.top().second;
hp.pop();
if(st[u]) continue;
st[u] = 1;
for(auto i : g[u]) {
int v = i.to;
if(dist[v] > dist[u] + i.w) {
dist[v] = dist[u] + i.w;
hp.push({dist[v], v});
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for(int i = 1, u, v, c; i <= m; i ++) {
cin >> u >> v >> c;
g[u].push_back({i + n, 1, c});
g[v].push_back({i + n, 1, c});
g[i + n].push_back({u, 1, c});
g[i + n].push_back({v, 1, c});
}
for(int i = 1; i <= n; i ++) {
sort(g[i].begin(), g[i].end(), cmp);
for(int j = 1; j < g[i].size(); j ++) {
if(g[i][j].c == g[i][j - 1].c) {
g[g[i][j].to].push_back({g[i][j - 1].to, 0, 0});
g[g[i][j - 1].to].push_back({g[i][j].to, 0, 0});
}
}
}
dij();
if(dist[n] == 0x3f3f3f3f) cout << -1;
else cout << dist[n] / 2;
}