/ SeriousOJ /

Record Detail

Memory Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 4ms 532.0 KiB
#2 Accepted 4ms 400.0 KiB
#3 Accepted 4ms 576.0 KiB
#4 Accepted 5ms 668.0 KiB
#5 Accepted 33ms 2.715 MiB
#6 Accepted 58ms 2.988 MiB
#7 Accepted 41ms 2.906 MiB
#8 Memory Exceeded ≥461ms ≥256.016 MiB
#9 Accepted 50ms 1.141 MiB
#10 Accepted 66ms 2.938 MiB
#11 Accepted 49ms 3.332 MiB
#12 Accepted 54ms 2.859 MiB
#13 Accepted 25ms 3.0 MiB
#14 Accepted 80ms 3.156 MiB
#15 Accepted 33ms 1.121 MiB
#16 Accepted 25ms 2.828 MiB
#17 Accepted 22ms 2.809 MiB
#18 Accepted 22ms 2.84 MiB
#19 Accepted 71ms 15.879 MiB
#20 Accepted 74ms 15.922 MiB
#21 Accepted 72ms 15.855 MiB
#22 Accepted 98ms 29.574 MiB
#23 Accepted 168ms 15.668 MiB
#24 Accepted 174ms 15.691 MiB
#25 Accepted 86ms 15.855 MiB
#26 Accepted 8ms 1.656 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, sz[N], 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) {
    sz[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;
        sz[now] += sz[it];
        if (!f) cnt += sz[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(), sz[i] = 0, 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:29:09
Judged At
2024-11-11 03:10:15
Judged By
Score
97
Total Time
≥461ms
Peak Memory
≥256.016 MiB