/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 4ms 5.07 MiB
#2 Accepted 3ms 5.07 MiB
#3 Accepted 4ms 5.82 MiB
#4 Accepted 6ms 6.027 MiB
#5 Accepted 50ms 6.094 MiB
#6 Accepted 112ms 6.02 MiB
#7 Accepted 73ms 6.23 MiB
#8 Accepted 42ms 5.062 MiB
#9 Accepted 96ms 5.766 MiB
#10 Accepted 117ms 6.324 MiB
#11 Accepted 79ms 6.582 MiB
#12 Accepted 92ms 6.391 MiB
#13 Accepted 40ms 6.855 MiB
#14 Accepted 131ms 6.164 MiB
#15 Accepted 62ms 5.332 MiB
#16 Accepted 37ms 6.145 MiB
#17 Accepted 35ms 6.531 MiB
#18 Accepted 34ms 6.879 MiB
#19 Accepted 150ms 12.766 MiB
#20 Accepted 147ms 12.887 MiB
#21 Accepted 144ms 12.957 MiB
#22 Accepted 194ms 24.34 MiB
#23 Accepted 244ms 12.398 MiB
#24 Accepted 274ms 12.305 MiB
#25 Accepted 180ms 12.102 MiB
#26 Accepted 13ms 5.922 MiB

Code

#include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define dbg(a,b,c,d) cerr<<a<<"  "<<b<<"  "<<c<<"  "<<d<<endl;
#define kill(a) {cout<<a<<endl;continue;}
#define KILL(a) {cout<<a<<endl;return 0;}
#define debug cerr<<"Error Found"<<endl;
#define mem(a,b) memset(a,b,sizeof(a))
#define lcm(a, b) (a/__gcd(a,b))*b
#define w(t) cin>>t;while(t--)
#define pi  2 * acos(0.0)
#define endl "\n"
int t, cs = 0;
const int mxn = 2e5 + 3, mod = 1e9 + 7;
pair<int,int>mx_path;
vector<int>adj[mxn];
bool vis[mxn];
int dis[mxn];
int tot_dis, ans;
void find_tot_dis(int n, int par)
{
    for(auto i:adj[n])
    {
        if(i == par)continue;
        find_tot_dis(i, n);
        if(vis[i])dis[n] += dis[i] + 1, vis[n] = true;
    }
}
void dfs(int n, int par, int dis)
{
    if(vis[n])mx_path = max(mx_path, make_pair(dis, n));
    for(auto i:adj[n])if(i != par)dfs(i, n, dis + 1);
}
void DFS(int n, int par, int dis)
{
    if(vis[n])ans = min(ans, tot_dis - dis);
    for(auto i:adj[n])
    {
        if(i == par)continue;
        DFS(i, n, dis + 1);
    }
}
int32_t main()
{
    //fast;
    w(t)
    {
        int n;
        cin >> n;
        int root = 0;
        ans = 2e9;
        for(int i = 1, a; i <= n; i++)
        {
            adj[i].clear();
            vis[i] = dis[i] = 0;
            cin >> a;
            if(a)vis[i] = true, root = i;
        }

        for(int i = 1; i < n; i++)
        {
            int a, b;
            cin >> a >> b;
            adj[a].push_back(b), adj[b].push_back(a);
        }
        if(!root)kill(0);
        find_tot_dis(root, -1);
        tot_dis = dis[root] * 2;
        mx_path = make_pair(-1, 1);
        dfs(root, -1, 0);
        DFS(mx_path.second, -1, 0);
        cout << ans << endl;
    }
}

Information

Submit By
Type
Submission
Problem
P1078 Apple on Tree
Language
C++17 (G++ 13.2.0)
Submit At
2024-11-15 09:35:43
Judged At
2024-11-15 09:35:43
Judged By
Score
100
Total Time
274ms
Peak Memory
24.34 MiB