Codeforces 1238F The Maximum Subtree Tree DP + Thinking

Portal

Title description

Insert picture description here

analysis

First, if two points are connected, there are only three situations: the left part overlaps, the cells are sub-intervals of a large interval, and the right part overlaps.
Then obviously, the first and third types will only appear once at most. Many times, these three points will form a ring, not a tree.
Then we continue to consider the second case. Will there be points connected to him among the communities? Certainly not, because if points can be connected to the communities , Then it must be connected to the large interval to form a ring.
So can the first and third types be connected to him a little bit? This is okay, as long as the interval expands in the opposite direction.

So this problem is converted to find a main chain, connect any point on the main chain to at most one point, and find the maximum subtree size, then it is converted into a caterpillar problem.
Paste the caterpillar’s ​​problem solution
portal

Code

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 3e5 + 10;
int h[N],e[N * 2],ne[N * 2],idx;
int f[N];
int n,m;
int ans;

void add(int x,int y){
    
    
    ne[idx] = h[x],e[idx] = y,h[x] = idx++;
}

void dfs(int u,int fa){
    
    
    int max1 = 0,max2 = 0;
    int cnt = 0;
    for(int i = h[u];~i;i = ne[i]){
    
    
        int j = e[i];
        cnt++;
        if(j == fa) continue;
        dfs(j,u);
        f[u] = max(f[u],f[j]);
        if(f[j] > max1) max2 = max1,max1 = f[j];
        else if(f[j] > max2) max2 = f[j];
    }
    cnt--;
    f[u] += (1 + max(0,cnt - 1));
    ans = max(ans,f[u] + max2);
}

int main(){
    
    
    int t;
    scanf("%d",&t);
    while(t--){
    
    
        idx = 0;
        ans = 0;
        scanf("%d",&n);
        for(int i = 1;i <= n;i++) h[i] = -1,f[i] = 0;
        for(int i = 1;i < n;i++){
    
    
            int x,y;
            scanf("%d%d",&x,&y);
            add(x,y),add(y,x);
        }
        dfs(1,-1);
        printf("%d\n",max(ans,1));
    }
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/

Guess you like

Origin blog.csdn.net/tlyzxc/article/details/112426789