跳到正文

题解

CF2254G Nightcrawler

内拉组里约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年8月5日
收录
2026年11月13日
更新
2026年11月21日
篇幅
约 5 分钟
获赞
1
题目
CF2254G

版本

  1. v1当前

upd Nov 11’26:修缮表述 &\& 更正时间复杂度:感谢 @leonhuang 指出。

难度不高但有些复杂的一道题。

Thoughts:

这第一眼看感觉有点像树剖,但实际上跟树剖一点关系都没有。

首先考虑无解的情况,也就是无法划分出合法的子集。

显然两个叶子节点不可能被分在同一个子集中,所以最少的子集数就是叶子的数量。

然后考虑如何构造子集数最少的方案。

显然对于每个非叶子节点 uu,考虑所有仅包含 uu 子树中节点的子集 ss 中,有且仅有一个能够包含 uu。

令 mxsmx_s 表示子集 ss 当前的分数,讨论 mxsmx_s 和 aua_u 的关系。

  • au>mxsa_u \gt mx_s,那么加入 uu 之后 mxsmx_s 就会增长为 aua_u,也就是会变大。
  • au≤mxsa_u \le mx_s,那么 uu 不会对 mxsmx_s 产生任何影响。

为使最终的分数和最大,肯定会优先选择前者,并且越小的 mxsmx_s,uu 产生的贡献就越大,所以贪心选 mxsmx_s 最小的子集。

遵循以上的贪心策略,自下而上地决策即可得到子集数最少的方案。

接下来考虑逐渐增加子集数后的最优方案。

增加子集数本质上就是从一个已有的子集中抠出来一个点作为一个独立的子集,

所以只需要把在最小子集数的方案中没有贡献的点拎出来然后把 aua_u 从大到小一个一个加进去即可。

Analyses:

总时间复杂度 Θ(∑Nlog⁡2N)\Theta (\sum N \log^2{N})。

总空间复杂度 Θ(N)\Theta (N)。

Code
C++
/* construct : AUG 05'26 */
/* faillable : Nodes in one disjoint set may not form a chain */
#include	<iostream>
#include	<vector>
#include	<queue>
#define		int		long long
using namespace std;
constexpr int maxn = 2e5+4;
constexpr int inf = 0x3f3f3f3f3f3f3f3f;

int t, n;
int a[maxn];
int p[maxn];
vector<int> G[maxn];
priority_queue<int,vector<int>,greater<int> > chn[maxn];

signed main (void)
{
	cin >> t;
	while (t--)
	{
		cin >> n;
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		for (int i = 1; i <= n; i++)
			G[i].clear();
		for (int i = 2; i <= n; i++)
		{
			cin >> p[i];
			G[p[i]].emplace_back(i);
		}
		// cerr << "> ";
		for (int flag = 0, i = 1; i <= n; i++) if (G[i].empty())
		{
			if (!flag)
				flag = 1;
			else
				cout << "-1 ";
			chn[i].emplace(a[i]);
		}
		priority_queue<int> alt;
		for (int u = n; u; u--) if (!G[u].empty())
		{
			int mn = inf;
			for (auto v : G[u])
			{
				if (chn[u].size() < chn[v].size())
					swap (chn[u], chn[v]);
				while (!chn[v].empty())
				{
					chn[u].emplace(chn[v].top());
					chn[v].pop();
				}
			}
			alt.emplace(min (a[u], chn[u].top()));
			chn[u].emplace(max (a[u], chn[u].top()));
			chn[u].pop();
		}
		int ans = 0;
		while (!chn[1].empty())
		{
			ans += chn[1].top();
			chn[1].pop();
		}
		cout << ans << ' ';
		while (!alt.empty())
		{
			ans += alt.top(); alt.pop();
			cout << ans << ' ';
		}
		cout << endl;
	}
	return 0;
}

/*
1
6
6 4 5 1 2 3
1 1 2 2 2

ans : -1 -1 -1 18 20 21

*/
原文
存档评论2 条抓取于