PermuTree (easy version)

考虑对于每个点算贡献。设以其所有儿子为根的子树大小为 sz1,sz2,,szksz_1, sz_2, \cdots, sz_k。设和为 ss,我们要求一个非空子集,设子集和为 s2s2。则贡献为 s2×(ss2)s2 \times (s-s2)。意味着 ss 这些点在排列中全部在这个点左边,其余的在右边。

感性理解可以发现,无论上述方案如何分配,都不会对以其他点为 LCA 的贡献产生影响。

所以我们要对每个前,求 s2×(ss2)s2 \times (s-s2) 最大值。

考虑每个点做一次,朴素地 01 背包可以求出哪些点可以为子集和。显然 s5000s \leq 5000。所以可以在 O(n2)O(n^2) 的时间复杂度内求出来,就做完了。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <set>
#include <map>
#include <unordered_map>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <cstdlib>
#include <string>
using namespace std;

#define int long long

const int N = 5005, INF = 2e9, MOD = 1e9 + 7;

inline int read()
{
	int op = 1, x = 0;
	char ch = getchar();
	while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
	while (ch == '-')
	{
		op = -op;
		ch = getchar();
	}
	while (ch >= '0' and ch <= '9')
	{
		x = (x << 1) + (x << 3) + (ch ^ 48);
		ch = getchar();
	}
	return x * op;
}

inline void write(int x)
{
	if (x < 0) putchar('-'), x = -x;
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}

int n, m, t;
vector<int> G[N];
long long ans = 0LL;
long long sz[N];

long long a[N];
bool canc[N];

void predfs(int u)
{
	sz[u] = 1;
	for (auto& j : G[u])
	{
		predfs(j);
		sz[u] += sz[j];
	}
}

void dfs(int u)
{
	int idx = 0;
	long long maxn1 = 0, maxn2 = 0, sum = 0, res = 0LL;
	for (auto& j : G[u])
	{
		a[++idx] = sz[j];
	}
	canc[0] = 1;
	for (int i = 1; i <= idx; i++)
	{
		sum += a[i];
		for (int j = sum; j >= a[i]; j--)
		{
			canc[j] |= canc[j - a[i]];
		}
		for (int j = 1; j <= sum; j++)
		{
			canc[sum - j] |= canc[j];
		}
	}
	for (int i = 1; i < sum; i++)
	{
		if (canc[i])
		{
			res = max(res, i * (sum - i));
			canc[i] = 0;
		}
	}
	for (int i = 0; i <= sum; i++) canc[i] = 0;
	ans += res;
	for (auto& j : G[u])
	{
		dfs(j);
	}
}

signed main()
{
	// freopen("*.in", "r", stdin);
	// freopen("*.out", "w", stdout);
	ios::sync_with_stdio(0), cin.tie(nullptr), cout.tie(nullptr);
	cin >> n;
	for (int i = 2; i <= n; i++)
	{
		int fa;
		cin >> fa;
		G[fa].emplace_back(i);
	}
	predfs(1);
	dfs(1);
	cout << ans << "\n";
	return 0;
}
posted @   HappyBobb  阅读(3)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示