/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 4ms 532.0 KiB
#2 Accepted 4ms 532.0 KiB
#3 Accepted 4ms 324.0 KiB
#4 Accepted 7ms 640.0 KiB
#5 Accepted 60ms 2.723 MiB
#6 Accepted 103ms 3.055 MiB
#7 Accepted 79ms 2.918 MiB
#8 Accepted 41ms 596.0 KiB
#9 Accepted 96ms 928.0 KiB
#10 Accepted 130ms 3.066 MiB
#11 Accepted 94ms 3.25 MiB
#12 Accepted 96ms 2.746 MiB
#13 Accepted 41ms 2.801 MiB
#14 Accepted 142ms 3.066 MiB
#15 Accepted 62ms 976.0 KiB
#16 Accepted 36ms 2.762 MiB
#17 Accepted 35ms 2.605 MiB
#18 Accepted 36ms 2.562 MiB
#19 Accepted 156ms 15.711 MiB
#20 Accepted 163ms 15.723 MiB
#21 Accepted 156ms 15.691 MiB
#22 Accepted 199ms 26.398 MiB
#23 Accepted 253ms 15.461 MiB
#24 Accepted 254ms 15.395 MiB
#25 Accepted 192ms 15.762 MiB
#26 Accepted 13ms 1.488 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-10-03 13:24:50
Judged By
Score
100
Total Time
254ms
Peak Memory
26.398 MiB