/ SeriousOJ /

Record Detail

Memory Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 5ms 5.02 MiB
#2 Accepted 5ms 5.02 MiB
#3 Accepted 5ms 5.02 MiB
#4 Accepted 6ms 5.02 MiB
#5 Accepted 30ms 6.02 MiB
#6 Accepted 52ms 6.27 MiB
#7 Accepted 36ms 6.262 MiB
#8 Memory Exceeded ≥466ms ≥256.016 MiB
#9 Accepted 44ms 5.266 MiB
#10 Accepted 52ms 6.066 MiB
#11 Accepted 39ms 6.27 MiB
#12 Accepted 45ms 6.02 MiB
#13 Accepted 22ms 6.145 MiB
#14 Accepted 60ms 6.27 MiB
#15 Accepted 51ms 5.156 MiB
#16 Accepted 20ms 6.02 MiB
#17 Accepted 19ms 6.02 MiB
#18 Accepted 19ms 6.02 MiB
#19 Accepted 88ms 12.887 MiB
#20 Accepted 64ms 12.754 MiB
#21 Accepted 61ms 12.754 MiB
#22 Accepted 85ms 27.293 MiB
#23 Accepted 128ms 12.281 MiB
#24 Accepted 127ms 12.27 MiB
#25 Accepted 73ms 12.152 MiB
#26 Accepted 9ms 5.773 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-08-16 20:33:54
Judged By
Score
97
Total Time
≥466ms
Peak Memory
≥256.016 MiB