#include <iostream>
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll maxn = 2*1e5+5, INF = 4e18+9;
struct DSU{
int n;
vector<int> pa, sz;
DSU(int n) : n(n){
pa.resize(n+1);
sz.resize(n+1, 1);
for(int i = 0; i <= n; i++){
pa[i] = i;
}
};
int find(int x){
while(x != pa[x]){
x = pa[x] = pa[pa[x]];
}
return x;
}
bool same(int x, int y){
return find(x) == find(y);
}
bool merge(int x, int y){
x = find(x);
y = find(y);
if(x == y) return false;
if(sz[x] < sz[y]) swap(x, y);
pa[y] = x;
sz[x] += sz[y];
return true;
}
int size(int x){
return sz[find(x)];
}
};
struct edge{
int u, v, w;
};
void solve(){
int n, m;
cin >> n >> m;
vector<edge> e(m+1);
for(int i = 1; i <= m; i++){
int u, v, w;
cin >> u >> v >> w;
e[i] = {u, v, w};
}
sort(e.begin()+1, e.end(), [&](edge a, edge b){return a.w < b.w;});
vector<vector<edge>> lt(m+1);
for(int i = 1; i <= m; i++){
DSU dsu(n+1);
dsu.merge(e[i].u, e[i].v);
lt[i].push_back(e[i]);
for(auto it : lt[i-1]){
if(dsu.merge(it.u, it.v)){
lt[i].push_back(it);
}
}
}
vector<vector<edge>> rt(m+1);
for(int i = m; i >= 1; i--){
DSU dsu(n+1);
dsu.merge(e[i].u, e[i].v);
rt[i-1].push_back(e[i]);
for(auto it : rt[i]){
if(dsu.merge(it.u, it.v)){
rt[i-1].push_back(it);
}
}
}
int Q;
cin >> Q;
int p = 0;
for(int i = 1; i <= Q; i++){
int x;
cin >> x;
while(p+1 <= m && e[p+1].w <= x){
p++;
}
int p1 = 0, p2 = 0;
DSU dsu(n+1);
ll ans = 0;
for(int i = 1; i <= (int)lt[p].size()+(int)rt[p].size(); i++){
if(p2 == (int)rt[p].size() || (p1 < (int)lt[p].size() && x - lt[p][p1].w <= rt[p][p2].w - x)){
if(dsu.merge(lt[p][p1].u, lt[p][p1].v)){
ans += x - lt[p][p1].w;
}
p1++;
}else{
if(dsu.merge(rt[p][p2].u, rt[p][p2].v)){
ans += rt[p][p2].w - x;
}
p2++;
}
}
cout << ans << "\n";
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
}
# | 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... |