/ SeriousOJ /

Record Detail

Memory Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 4ms 580.0 KiB
#2 Accepted 4ms 532.0 KiB
#3 Accepted 4ms 588.0 KiB
#4 Accepted 5ms 644.0 KiB
#5 Accepted 32ms 2.238 MiB
#6 Accepted 55ms 2.344 MiB
#7 Accepted 43ms 2.32 MiB
#8 Memory Exceeded ≥444ms ≥256.016 MiB
#9 Accepted 49ms 580.0 KiB
#10 Accepted 66ms 2.207 MiB
#11 Accepted 48ms 2.297 MiB
#12 Accepted 54ms 2.316 MiB
#13 Accepted 25ms 2.508 MiB
#14 Accepted 70ms 2.469 MiB
#15 Accepted 32ms 836.0 KiB
#16 Accepted 24ms 2.324 MiB
#17 Accepted 22ms 2.34 MiB
#18 Accepted 23ms 2.336 MiB
#19 Accepted 72ms 12.742 MiB
#20 Accepted 71ms 12.902 MiB
#21 Accepted 70ms 12.949 MiB
#22 Accepted 97ms 27.383 MiB
#23 Accepted 159ms 12.418 MiB
#24 Accepted 168ms 12.203 MiB
#25 Accepted 87ms 12.086 MiB
#26 Accepted 9ms 1.52 MiB

Code

#include <bits/stdc++.h>

#ifdef LOCAL
#include "template.cpp.h"
#else
#define debug(...)
#endif

//#define int long long
using namespace std;
#define cinv(v) for (auto &it:v) cin>>it;
#define coutv(v) for (auto &it:v) cout<< it<<' '; cout<<'\n';

const int N = 2e5 + 5;
vector<int> adj[N];
int n, ans, dist[N], node1, node2;
bool a[N];

void dfs(int now, int par) {
    for (auto &it: adj[now]) {
        if (it == par) continue;
        dist[it] = dist[now] + 1;
        dfs(it, now);
    }
}

bool dfs2(int now, int par) {
    dist[now] = 1;
    bool ret = a[now];
    int cnt = 0;
    for (auto &it: adj[now]) {
        if (it == par) continue;
        bool f = dfs2(it, now);
        ret |= f;
        dist[now] += dist[it];
        if (!f) cnt += dist[it];
    }
    if (ret || now == node1) ans -= 2 * cnt;
    return ret;
}

void reset() {
    ans = 0, node1 = node2 = 1;
    for (int i = 1; i <= n; ++i) adj[i].clear(), dist[i] = 0, a[i] = false;
}

void shelby() {
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> a[i];
    for (int i = 0; i < n - 1; ++i) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    if (count(a, a + n + 1, true) < 2) {
        cout << "0\n";
        return;
    }
    dfs(1, -1);
    int now = 0;
    for (int i = 1; i <= n; ++i) {
        if (dist[i] > now && a[i]) {
            now = dist[i];
            node1 = i;
        }
    }
    dist[node1] = 0;
    dfs(node1, -1);
    now = 0;
    for (int i = 1; i <= n; ++i) {
        if (dist[i] > now && a[i]) {
            now = dist[i];
            node2 = i;
        }
    }
    ans = 2 * n - 2 - now;
    dfs2(node1, -1);
    cout << ans << '\n';
    reset();
}

signed main() {
    cin.tie(0)->ios_base::sync_with_stdio(0);
    int t = 1;
    cin >> t;
    for (int _ = 1; _ <= t; ++_) {
//        cout << "Case " << _ << ": ";
        shelby();
    }
}

Information

Submit By
Type
Submission
Problem
P1078 Apple on Tree
Language
C++20 (G++ 13.2.0)
Submit At
2024-08-16 20:33:54
Judged At
2024-11-11 03:10:15
Judged By
Score
97
Total Time
≥444ms
Peak Memory
≥256.016 MiB