제출 #886361

#제출 시각아이디문제언어결과실행 시간메모리
886361dong_liuReconstruction Project (JOI22_reconstruction)C++17
42 / 100
5041 ms415028 KiB
#include <bits/stdc++.h>
using namespace std;

#define ar array
#define sz(v) int(std::size(v))
using i64 = long long;
using pii = pair<int, int>;

bool mem_st;

const int N = 500, M = 1e5, Q = 1e6;

struct edge {
    int i, j, w;
    bool operator<(const edge e) const {
        return w < e.w;
    }
};

struct arr : ar<int, N-1> {
    int sz = 0;
    void pb(int x) { at(sz++) = x; }
    auto end() { return begin()+sz; }
};

int n, m, q;
edge e[M];
arr pf[M+1], sf[M+1];

struct {
    int p[N];
    void init() {
        for (int i = 0; i < n; i++) p[i] = i;
    }
    int find(int i) {
        return p[i] == i ? i : p[i] = find(p[i]);
    }
    bool join(int i, int j) {
        i = find(i), j = find(j);
        if (i == j) return false;
        p[i] = j;
        return true;
    }
} dsu;

bool mem_en;


int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n >> m;
    for (int h = 0; h < m; h++) {
        cin >> e[h].i >> e[h].j >> e[h].w;
        e[h].i--, e[h].j--;
    }
    sort(e, e+m);
    for (int t = 1; t <= m; t++) {
        auto ins = [&](int h) {
            if (dsu.join(e[h].i, e[h].j))
                pf[t].pb(h);
        };
        dsu.init();
        ins(t-1);
        for (int h : pf[t-1]) ins(h);
    }
    for (int t = m-1; t >= 0; t--) {
        auto ins = [&](int h) {
            if (dsu.join(e[h].i, e[h].j))
                sf[t].pb(h);
        };
        dsu.init();
        ins(t);
        for (int h : sf[t+1]) ins(h);
    }
    cin >> q;
    int t = 0;
    while (q--) {
        int x;
        cin >> x;
        while (t < m && e[t].w <= x) t++;
        dsu.init();
        int one = 0, two = 0; i64 cost = 0;
        auto ins = [&](int h) {
            if (dsu.join(e[h].i, e[h].j))
                cost += abs(e[h].w - x);
        };
        while (one < pf[t].sz && two < sf[t].sz)
            if (x-e[pf[t][one]].w < e[sf[t][two]].w-x) ins(pf[t][one++]);
            else ins(sf[t][two++]);
        while (one < pf[t].sz) ins(pf[t][one++]);
        while (two < sf[t].sz) ins(sf[t][two++]);
        cout << cost << '\n';
    }
#if 0
    cout << double(&mem_en - &mem_st) / (1 << 20) << '\n';
#endif
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...