/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 4ms 532.0 KiB
#2 Accepted 4ms 532.0 KiB
#3 Accepted 4ms 532.0 KiB
#4 Accepted 7ms 576.0 KiB
#5 Accepted 60ms 2.59 MiB
#6 Accepted 103ms 3.059 MiB
#7 Accepted 79ms 2.789 MiB
#8 Accepted 45ms 588.0 KiB
#9 Accepted 101ms 832.0 KiB
#10 Accepted 128ms 3.066 MiB
#11 Accepted 100ms 3.242 MiB
#12 Accepted 108ms 2.961 MiB
#13 Accepted 43ms 2.754 MiB
#14 Accepted 148ms 3.066 MiB
#15 Accepted 63ms 944.0 KiB
#16 Accepted 40ms 2.582 MiB
#17 Accepted 42ms 2.617 MiB
#18 Accepted 37ms 2.754 MiB
#19 Accepted 164ms 15.621 MiB
#20 Accepted 167ms 15.82 MiB
#21 Accepted 163ms 15.734 MiB
#22 Accepted 208ms 26.32 MiB
#23 Accepted 261ms 15.477 MiB
#24 Accepted 271ms 15.281 MiB
#25 Accepted 202ms 15.598 MiB
#26 Accepted 13ms 1.426 MiB

Code

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2e5;
int a[N], d[N], sum;
vector <int> g[N];
bool Dfs(int v, int p){
    bool ok = (a[v] == 1);
    for(int u:g[v]){
        if(u != p){
            d[u] = d[v] + 1;
            ok |= Dfs(u, v);
        }
    }
    if(ok == true and v != p) sum += 2;
    return ok;
}
void dfs(int v, int p){
    for(int u:g[v]){
        if(u != p){
            d[u] = d[v] + 1;
            dfs(u, v);
        }
    }
}
void sol(){
    int n;
    cin >> n;
    for(int i = 0; i < n; i++) cin >> a[i], d[i] = 0, g[i].clear();
    for(int i = 1; i < n; i++) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(0, 0);
    int node = 0, mx = 0;
    for(int i = 0; i < n; i++){
        if(a[i]){
            if(d[i] >= mx){
                mx = d[i];
                node = i;
            }
        }
        d[i] = 0;
    }
    sum = 0;
    bool ok =  Dfs(node, node);
    mx = 0;
    for(int i = 0; i < n; i++){
        if(a[i]) mx = max(mx, d[i]);
    }
    cout << sum - mx << endl;
}
signed main(){
    int t;
    cin >> t;
    while(t--){
        sol();
    }
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1078 Apple on Tree
Contest
Bangladesh 2.0
Language
C++20 (G++ 13.2.0)
Submit At
2024-08-16 16:56:15
Judged At
2024-11-11 03:13:19
Judged By
Score
100
Total Time
271ms
Peak Memory
26.32 MiB