PermuTree (easy version)
考虑对于每个点算贡献。设以其所有儿子为根的子树大小为 。设和为 ,我们要求一个非空子集,设子集和为 。则贡献为 。意味着 这些点在排列中全部在这个点左边,其余的在右边。
感性理解可以发现,无论上述方案如何分配,都不会对以其他点为 LCA 的贡献产生影响。
所以我们要对每个前,求 最大值。
考虑每个点做一次,朴素地 01 背包可以求出哪些点可以为子集和。显然 。所以可以在 的时间复杂度内求出来,就做完了。
#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;
}

浙公网安备 33010602011771号