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>
#define FR(i, N) for (int i = 0; i < int(N); i++)
#define all(x) begin(x), end(x)
using namespace std;
using ll = long long;
const int MAXN = (int)(1e5) + 5;
vector<pair<int, int>> adj[MAXN];
int closest[MAXN];
int par[MAXN];
int rk[MAXN];
int ans[MAXN];
unordered_set<int> keep[MAXN];
int find(int x) {
if (par[x] == x) {
return x;
}
else {
return (par[x] = find(par[x]));
}
}
void merge(int x, int y) {
int px = find(x);
int py = find(y);
int res = min(closest[x], closest[y]);
if (px != py) {
if (rk[px] < rk[py]) {
swap(px, py);
}
for (int e : keep[py]) {
if (keep[px].count(e)) {
keep[px].erase(e);
ans[e] = res;
}
else {
keep[px].insert(e);
}
}
rk[px] += rk[py];
par[py] = px;
}
}
int main() {
cin.tie(0);
cin.sync_with_stdio(0);
int N, M;
cin >> N >> M;
vector<pair<int, int>> edges(M);
FR(i, N) {
rk[i] = 1;
par[i] = i;
}
FR(iter, M) {
int a, b, w;
cin >> a >> b >> w;
a--, b--;
adj[b].push_back({a, w});
adj[a].push_back({b, w});
edges[iter] = {a, b};
}
fill(all(closest), MAXN);
int K;
cin >> K;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
FR(iter, K) {
int a;
cin >> a;
a--;
pq.push({0, a});
closest[a]=0;
}
while (pq.size()) {
auto nxt = pq.top();
pq.pop();
if (closest[nxt.second] == nxt.first) {
for (auto& e : adj[nxt.second]) {
if (closest[e.first] > closest[nxt.second] + e.second) {
closest[e.first] = closest[nxt.second] + e.second;
pq.push({closest[e.first], e.first});
}
}
}
}
sort(all(edges), [] (const auto& lhs, auto& rhs) {
return min(closest[lhs.first], closest[lhs.second]) > min(closest[rhs.first], closest[rhs.second]);
});
int Q;
cin >> Q;
FR(iter, Q){
int u, v;
cin >> u >> v;
u--, v--;
keep[u].insert(iter);
keep[v].insert(iter);
}
for (auto& e : edges) {
merge(e.first, e.second);
}
FR(i, Q) {
cout << ans[i] << '\n';
}
return 0;
}
# | 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... |