1238F - The Maximum Subtree - CodeForces Solution


dfs and similar dp graphs trees *2200

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
vector <int> adj[300001];
int dp[300001][2];
void dfs (int pos, int par) {
    vector <int> ll;
    dp[pos][1] = (int)adj[pos].size() - 1;
    for (auto j : adj[pos]) {
        if (j == par) continue;
        dfs(j, pos);
        dp[pos][0] = max(dp[pos][0], dp[j][0]);
        if ((int)adj[j].size() != 1) {
            ll.push_back(dp[j][1]);
            dp[pos][1] = max(dp[pos][1], (int)adj[pos].size() + dp[j][1] - 1);
        }
    }
    sort(ll.begin(), ll.end()); reverse(ll.begin(), ll.end());
    int x = (int)adj[pos].size() + 1;
    if (ll.size() == 0) {
        dp[pos][0] = max(dp[pos][0], (int)adj[pos].size() + 1);
    } else if (ll.size() == 1) {
        dp[pos][0] = max(dp[pos][0], (int)adj[pos].size() + 1 + ll[0]);
    } else {
        dp[pos][0] = max(dp[pos][0], (int)adj[pos].size() + 1 + ll[0] + ll[1]);
    }
}
int main () {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        for (int i = 1; i <= n; i++) {
            adj[i].clear();
            dp[i][0] = 0;
            dp[i][1] = 0;
        }
        for (int i = 1; i < n; i++) {
            int a, b; cin >> a >> b;
            adj[a].push_back(b);
            adj[b].push_back(a);
        }
        if (n == 2) {
            cout << 2 << '\n'; continue;
        }
        int root; for (int i = 1; i <= n; i++) if (adj[i].size() > 1) root = i;
        dfs(root, -1);
        cout << dp[root][0] << '\n';
    }
}


Comments

Submit
0 Comments
More Questions

1189A - Keanu Reeves
678A - Johny Likes Numbers
1699C - The Third Problem
1697D - Guess The String
754B - Ilya and tic-tac-toe game
760A - Petr and a calendar
1573A - Countdown
166A - Rank List
1631B - Fun with Even Subarrays
727A - Transformation from A to B
822B - Crossword solving
1623A - Robot Cleaner
884B - Japanese Crosswords Strike Back
862B - Mahmoud and Ehab and the bipartiteness
429A - Xor-tree
1675C - Detective Task
950A - Left-handers Right-handers and Ambidexters
672B - Different is Good
1C - Ancient Berland Circus
721A - One-dimensional Japanese Crossword
1715B - Beautiful Array
60B - Serial Time
453A - Little Pony and Expected Maximum
1715A - Crossmarket
1715C - Monoblock
1512C - A-B Palindrome
1679B - Stone Age Problem
402A - Nuts
792A - New Bus Route
221A - Little Elephant and Function