This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
const int INF = 1e9;
vector<pair<int, int>> adj[N];
struct info {
int a, b, l, m, r, id;
};
bool operator<(info &a, info &b) {
return make_pair(a.m, a.id) > make_pair(b.m, b.id);
}
struct DSU {
vector<int> pa, sz;
DSU(int n) {
pa.resize(n);
sz.resize(n, 1);
iota(pa.begin(), pa.end(), 0);
}
int Find(int k) {
if (k == pa[k]) {
return k;
}
return pa[k] = Find(pa[k]);
}
void onion(int a, int b) {
a = Find(a), b = Find(b);
if (a == b) {
return;
}
if (sz[a] > sz[b]) {
swap(a, b);
}
pa[a] = b;
sz[b] += sz[a];
}
};
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
adj[a].push_back({b, c});
adj[b].push_back({a, c});
}
vector<int> dis(N, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
int shaoji;
cin >> shaoji;
for (int i = 0; i < shaoji; i++) {
int k;
cin >> k;
dis[k] = 0;
pq.push({0, k});
}
while (pq.size()) {
int a, b;
tie(a, b) = pq.top();
pq.pop();
if (a != dis[b]) {
continue;
}
for (auto &e : adj[b]) {
if (dis[e.first] > a + e.second) {
dis[e.first] = a + e.second;
pq.push({dis[e.first], e.first});
}
}
}
vector<info> v;
for (int i = 1; i <= n; i++) {
for (auto &e : adj[i]) {
if (dis[i] <= dis[e.first]) {
v.push_back({i, e.first, 0, dis[i], 0, INF});
}
}
}
int q;
cin >> q;
vector<int> ans(q);
int solved = 0;
for (int i = 0; i < q; i++) {
int a, b;
cin >> a >> b;
int c = INF / 2;
v.push_back({a, b, 0, c, INF, i});
}
sort(v.begin(), v.end());
vector<info> v1;
while (solved != q) {
int sz = v.size();
DSU d(n + 1);
for (int i = 0; i < sz; i++) {
// cout<<v[i].m<<' ';
if (v[i].id == INF) {
d.onion(v[i].a, v[i].b);
v1.push_back(v[i]);
} else {
if (d.Find(v[i].a) == d.Find(v[i].b)) {
v[i].l = v[i].m;
} else {
v[i].r = v[i].m;
}
if (v[i].r - v[i].l == 1) {
ans[v[i].id] = v[i].l;
solved++;
} else {
v[i].m = (v[i].l + v[i].r) / 2;
v1.push_back(v[i]);
}
}
}
// cout<<endl;
v = v1;
v1.clear();
sort(v.begin(), v.end());
}
for (int i = 0; i < q; i++) {
cout << ans[i] << '\n';
}
return 0;
}
/*
9 12
1 9 4
1 2 5
2 3 7
2 4 3
4 3 6
3 6 4
8 7 10
6 7 5
5 8 1
9 5 7
5 4 12
6 8 2
2
4 7
5
1 6
5 3
4 8
5 8
1 5
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |