1 solutions

  • -1
    @ 2025-11-17 14:13:17
    • 给定一个 nn 个点的树, 要求删除一条路径使得剩下的连通块中大小 ≥K\geq K 的数量最大。
    • 设 f(i)f(i) 为 ii 的子树内删去一条完整路径的最大数量, g(i)g(i) 为 ii 的子树 内删去一条不完整的路径, 即 ii 为路径的一个端点时的最大数量。
    • 假设 j1…jmj_{1} \ldots j_{m} 为 ii 的所有子树, 那么我们选出 $g\left(j_{k}\right)-\left[\operatorname{size}_{j_{k}} \geq K\right]$ 的 最大值与次大值来更新 f(i)f(i), 求出 f(i)f(i) 后可以快速的得到答案, 时间 复杂度 O(Tn)O(T n)
    #include <bits/stdc++.h>
    #define xx first
    #define yy second
    #define mp make_pair
    #define pb push_back
    #define mset(x, y) memset(x, y, sizeof x)
    #define mcpy(x, y) memcpy(x, y, sizeof x)
    using namespace std;
     
    typedef long long LL;
    typedef pair <int, int> pii;
     
    inline int Read()
    {
    	int x = 0, f = 1, c = getchar();
    	for (; !isdigit(c); c = getchar())
    		if (c == '-')
    			f = -1;
    	for (;  isdigit(c); c = getchar())
    		x = x * 10 + c - '0';
    	return x * f;
    }
     
    const int MAXN = 100005;
     
    int n, m, ans, siz[MAXN], par[MAXN], f[MAXN];
    vector <int> adj[MAXN];
     
    inline void DFS(int x)
    {
    	siz[x] = 1;
    	for (auto y : adj[x])
    		if (y ^ par[x])
    			par[y] = x, DFS(y), siz[x] += siz[y];
    }
     
    inline void DP(int x)
    {
    	int all = 0, fir = -n, sec = -n;
    	for (auto y : adj[x])
    		if (y ^ par[x])
    		{
    			DP(y), all += siz[y] >= m;
    			if (f[y] - (siz[y] >= m) >= fir)
    				sec = fir, fir = f[y] - (siz[y] >= m);
    			else if (f[y] - (siz[y] >= m) >= sec)
    				sec = f[y] - (siz[y] >= m);
    		}
    	f[x] = all + max(fir, 0);
    	ans = max(ans, all + fir + max(sec, 0) + (n - siz[x] >= m));
    }
     
    int main()
    {   
    	freopen("cut.in", "r", stdin);
    	freopen("cut.out", "w", stdout);
        int T = Read();
        while (T--) {
    		ans = 0;
            n = Read(), m = Read();
            for (int i = 1; i <= n; i++)
                adj[i].clear();
            for (int i = 1, x, y; i < n; i ++)
                x = Read(), y = Read(), adj[x].pb(y), adj[y].pb(x);
            DFS(1), DP(1);
            printf("%d\n", ans);
        }
        return 0;
    }
    
    • 1

    Information

    ID
    154
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    7
    Tags
    (None)
    # Submissions
    34
    Accepted
    8
    Uploaded By