#include <bits/stdc++.h>
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
using namespace std;
#define int long long int
const int N = 1e5 + 10;
const int md = 1e9 + 7;
const int INF = 1e18;
vector<int> dist(N, INF);
class DisjointSets {
private:
vector<int> p;
vector<int> dst;
public:
DisjointSets(int n) : p(n), dst(n) {
for (int i = 0; i < n; i++) { p[i] = i, dst[i] = dist[i];}
}
int get(int u) {
return p[u] = (u == p[u] ? u : get(p[u]));
}
void unite(int u, int v) {
u = get(u);
v = get(v);
if (u == v) {
return;
}
p[v] = u;
dst[u] = min(dst[u], dst[v]);
return;
}
int distance(int u) {
u = get(u);
return dst[u];
}
};
int32_t main(int32_t argc, char *argv[]) {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T = 1;
// cin >> T;
while (T--) {
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> g(n + 1, vector<pair<int, int>> ());
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
g[u].push_back(make_pair(v, w));
g[v].push_back(make_pair(u, w));
}
int k;
cin >> k;
set<pair<int, int>> q;
for (int i = 0; i < k; i++) {
int u;
cin >> u;
dist[u] = 0;
q.insert({0, u});
}
vector<bool> visited(n + 1);
while (!q.empty()) {
int v = (*q.begin()).second;
q.erase(q.begin());
if (!visited[v])
for (auto i : g[v]) {
dist[i.first] = min(dist[i.first], dist[v] + i.second);
if (!visited[i.first])
q.insert({dist[i.first], i.first});
}
visited[v] = 1;
}
// for (int i = 1; i <= n; i++)
// cout << i << " " << dist[i] << '\n';
int que;
cin >> que;
vector<vector<pair<int, int>>> qu(n + 1, vector<pair<int, int>> ());
for (int i = 0; i < que; i++) {
int u, v;
cin >> u >> v;
qu[u].push_back(make_pair(v, i));
qu[v].push_back(make_pair(u, i));
}
vector<pair<int, int>> dst;
for (int i = 1; i <= n; i++)
dst.push_back(make_pair(dist[i], i));
sort(dst.rbegin(), dst.rend());
DisjointSets dsu(n + 1);
vector<int> ans(que);
int ind = 0;
vector<bool> vis(n + 1);
while (ind < (int) dst.size()) {
auto [ds, u] = dst[ind];
vis[u] = 1;
for (auto i : g[u]) {
if (vis[i.first]) {
dsu.unite(i.first, u);
}
}
for (auto i : qu[u]) {
if (dsu.get(u) == dsu.get(i.first))
ans[i.second] = dsu.distance(u);
}
ind++;
}
for (auto i : ans)
cout << 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... |