1689C - Infected Tree - CodeForces Solution


dfs and similar dp trees *1600

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
 
using namespace std;
 
vector<vector<int>> g(300005);
int ch[300005],dp[300005];
 
void dfs(int p, int q)
{
    ch[p]=1,dp[p]=0; int s=0;
    for (auto it : g[p]) if (it!=q)
    {
        dfs(it,p); s+=dp[it];
        ch[p]+=ch[it];
    }
    for (auto it : g[p]) if (it!=q)
    {
        dp[p]=max(dp[p],s-dp[it]+ch[it]-1);
    }
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
 
    int t; cin>>t;
    while (t--)
    {
        int n; cin>>n;
        for (int i=1;i<=n;i++) g[i].clear();
        for (int i=1;i<n;i++)
        {
            int u,v; cin>>u>>v;
            g[u].push_back(v);
            g[v].push_back(u);
        }
 
        dfs(1,0);
        cout<<dp[1]<<"\n";
    }
}


Comments

Submit
0 Comments
More Questions

630I - Parking Lot
160B - Unlucky Ticket
371B - Fox Dividing Cheese
584B - Kolya and Tanya
137B - Permutation
550C - Divisibility by Eight
5A - Chat Servers Outgoing Traffic
615A - Bulbs
5B - Center Alignment
549A - Face Detection
535B - Tavas and SaDDas
722C - Destroying Array
366A - Dima and Guards
716B - Complete the Word
1461C - Random Events
1627A - Not Shading
141B - Hopscotch
47B - Coins
1466C - Canine poetry
74A - Room Leader
1333D - Challenges in school №41
1475B - New Year's Number
461A - Appleman and Toastman
320B - Ping-Pong (Easy Version)
948A - Protect Sheep
387A - George and Sleep
53A - Autocomplete
1729G - Cut Substrings
805B - 3-palindrome
805C - Find Amir