#include <bits/stdc++.h>
using namespace std;
#define int long long
struct thing {
int u, v, w;
bool operator < (const thing &b) const {
return w < b.w;
}
};
const int maxn = 505, maxm = 1e5 + 5, INF = 1e15;
int n;
vector<thing> edge;
vector<int> vals;
int valsz;
int dsu[maxn], sz[maxn];
int rt(int u) {
if (dsu[u] == u) return u;
else return dsu[u] = rt(dsu[u]);
}
void merge(int u, int v) {
if (sz[u] > sz[v]) swap(u, v);
dsu[u] = v;
sz[v] += sz[u];
}
vector<thing> pref[maxm], suff[maxm];
signed main() {
ios::sync_with_stdio(0); cin.tie(0);
int m;
cin >> n >> m;
edge.resize(m);
for (auto &[u, v, w]:edge) {
cin >> u >> v >> w;
vals.push_back(w);
}
vals.push_back(-INF); vals.push_back(INF);
sort(edge.begin(), edge.end());
sort(vals.begin(), vals.end());
vals.erase(unique(vals.begin(), vals.end()), vals.end());
int valsz = vals.size();
int R = -1;
for (int i=0;i<valsz;i++) {
while (R+1 < m && edge[R+1].w <= vals[i]) R++;
for (int j=1;j<=n;j++) dsu[j] = j, sz[j] = 1;
for (int j=R;j>=0;j--) {
auto [u, v, w] = edge[j];
u = rt(u), v = rt(v);
if (u != v) {
merge(u, v);
pref[i].push_back(edge[j]);
}
}
}
int L = m;
for (int i=valsz-1;i>=0;i--) {
while (L-1 >= 0 && edge[L-1].w >= vals[i]) L--;
for (int j=1;j<=n;j++) dsu[j] = j, sz[j] = 1;
for (int j=L;j<m;j++) {
auto [u, v, w] = edge[j];
u = rt(u), v = rt(v);
if (u != v) {
merge(u, v);
suff[i].push_back(edge[j]);
}
}
}
// for (auto [u, v, w]:edge) cout << u << " " << v << " " << w << endl;
// cout << endl;
// cout << vals[1] << endl;
// for (auto [u, v, w]:pref[1]) cout << u << " " << v << " " << w << endl;
// cout << endl;
int q;
cin >> q;
while (q--) {
int x;
cin >> x;
int pos = lower_bound(vals.begin(), vals.end(), x) - vals.begin();
int pt1 = 0, pt2 = 0;
int sz1 = pref[pos-1].size(), sz2 = suff[pos].size();
int cnt = 0, ans = 0;
for (int i=1;i<=n;i++) dsu[i] = i, sz[i] = 1;
while (cnt < n-1) {
if (pt1 < sz1 && (pt2 >= sz2 || x - pref[pos-1][pt1].w < suff[pos][pt2].w - x)) {
// cout << "test\n";
auto [u, v, w] = pref[pos-1][pt1];
u = rt(u), v = rt(v);
if (u != v) {
cnt++;
merge(u, v);
ans += x - w;
}
pt1++;
} else {
auto [u, v, w] = suff[pos][pt2];
u = rt(u), v = rt(v);
if (u != v) {
cnt++;
merge(u, v);
ans += w - x;
}
pt2++;
}
// cout << cnt << " " << pt1 << " " << pt2 << endl;
}
cout << ans << "\n";
}
}
# | 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... |