#include <bits/stdc++.h>
#define F first
#define S second
using namespace std;
using ll = long long;
using pi = pair<int, int>;
using vi = vector<int>;
template<class T> bool ckmin(T& a, T b) { return b < a ? a = b, true : false; }
template<class T> bool ckmax(T& a, T b) { return a < b ? a = b, true : false; }
const int N = 5e2 + 7;
int n, m, t[N], sz[N];
vector<array<int, 4>> edges;
int root(int x) {
if (t[x] == x) return x;
return t[x] = root(t[x]);
}
void join(int a, int b) {
a = root(a), b = root(b);
if (a == b) return;
if (sz[a] < sz[b]) swap(a, b);
sz[a] += sz[b];
t[b] = a;
}
vector<int> get_config(int x) {
sort(edges.begin(), edges.end(), [&](array<int, 4> a, array<int, 4> b) { return abs(x - a[2]) < abs(x - b[2]); });
for (int i = 1; i <= n; ++i) t[i] = i, sz[i] = 1;
vector<int> sol;
for (auto [a, b, w, i] : edges) {
if (root(a) != root(b)) {
join(a, b);
sol.push_back(i);
}
}
return sol;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> n >> m;
vector<int> weight(m + 1);
for (int i = 1; i <= m; ++i) {
int a, b, w; cin >> a >> b >> w;
edges.push_back({a, b, w, i});
weight[i] = w;
}
vector<pair<pi, vector<int>>> intervals;
int l = 1;
while (true) {
vector<int> config = get_config(l);
int low = l + 1, high = 1e9, sol = l;
while (low <= high) {
int mid = (low + high) / 2;
if (get_config(mid) == config) {
sol = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
intervals.push_back({{l, sol}, config});
assert((int) intervals.size() <= 100000);
l = sol + 1;
if (sol == 1e9) break;
}
int q; cin >> q;
while (q--) {
ll x; cin >> x;
for (auto [it, config] : intervals) {
int l = it.F, r = it.S;
if (l <= x && x <= r) {
ll cost = 0;
for (auto id : config) cost += abs(x - weight[id]);
cout << cost << "\n";
break;
}
}
}
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |