/ SeriousOJ /

Record Detail

Memory Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 5ms 5.02 MiB
#2 Accepted 5ms 5.02 MiB
#3 Accepted 6ms 5.02 MiB
#4 Accepted 11ms 5.074 MiB
#5 Accepted 45ms 6.645 MiB
#6 Accepted 71ms 6.992 MiB
#7 Accepted 57ms 6.77 MiB
#8 Memory Exceeded ≥472ms ≥256.016 MiB
#9 Accepted 44ms 5.367 MiB
#10 Accepted 55ms 7.02 MiB
#11 Accepted 47ms 7.02 MiB
#12 Accepted 47ms 6.898 MiB
#13 Accepted 24ms 6.742 MiB
#14 Accepted 63ms 7.062 MiB
#15 Accepted 30ms 5.57 MiB
#16 Accepted 21ms 6.52 MiB
#17 Accepted 25ms 6.562 MiB
#18 Accepted 23ms 6.52 MiB
#19 Accepted 63ms 15.895 MiB
#20 Accepted 85ms 16.027 MiB
#21 Accepted 64ms 15.789 MiB
#22 Accepted 95ms 29.77 MiB
#23 Accepted 140ms 15.562 MiB
#24 Accepted 161ms 15.477 MiB
#25 Accepted 96ms 15.812 MiB
#26 Accepted 9ms 5.945 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-08-16 20:29:09
Judged By
Score
97
Total Time
≥472ms
Peak Memory
≥256.016 MiB