跳到正文

题解

P7897 [Ynoi2006] spxmcq 题解

gw2204约 6 分钟
原文
文章信息与版本

文章信息

发布
2026年10月14日
收录
2026年11月16日
更新
2026年11月21日
篇幅
约 6 分钟
题目
P7897

版本

  1. v1当前

如何刻画这个问题?如果要暴力该怎么做?首先思考这两个问题,首先假设所有结点都已经加上了 xx ,不难一个推到的dp式子 fu=au+∑v∈sonufv∗[fv≥0]f_u=a_u+ \sum_{v \in son_u}f_v*[f_v \geq 0] ,对于 fv<0f_v < 0 的儿子一定不优。因此发现,只有当 fv≥0f_v \geq 0 时才会对父亲产生贡献。

不妨离线处理询问,按 xx 从小到大排序,把整张图当作森林,当 fu≥0f_u \geq 0 时便向上连一条边,对父亲产生贡献,那么对于一个结点 uu 的 fuf_u 便可以换种方式表示出来,sumsum 表示已经与 uu 相连通的所有结点权值和,cntcnt 则表示结点个数,那么 fu=sum+cnt∗xf_u=sum + cnt*x ,如果 uu 要向父亲连边,那么应满足 sum+cnt∗x≥0sum+cnt*x \geq 0 ,移项得 x>=⌈−sumcnt⌉x >= \lceil \frac{-sum}{cnt} \rceil ,离线处理答案时拿堆处理即可。对于每次连上一条边,在堆里只会影响两个点,即当前向上连边的点和连完边后联通快最高点,在树上对权值的影响时一条链,树状数组维护即可。

代码如下

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1000010;
int n, m, a[N], b[N], sum[N], cnt[N], st[N], ed[N], tot, f[N][2], ans[N], fa[N], top[N];
vector <int> v[N];
struct tt {
	int u, x, id;
	friend bool operator < (tt a, tt b) {
		return a.x != b.x ? a.x < b.x : a.u < b.u;
	}
}ask[N];
priority_queue <tt> q;
void add(int op, int x, int y) {
	if (x == 0) return ;
	for (int i = x; i <= n; i += (i & (-i))) f[i][op] += y;
}
int query(int op, int x) {
	int res = 0;
	for (int i = x; i; i -= (i & (-i))) res += f[i][op];
	return res;
}
void dfs(int x) {
	top[x] = x, st[x] = ++tot;
	add(0, st[x], a[x]), add(0, st[fa[x]], -a[x]), add(1, st[x], 1), add(1, st[fa[x]], -1);
	for (auto i : v[x]) {
		dfs(i);
	}
	ed[x] = tot;
}
int find(int x) {
	if (top[x] == x) return x;
	return top[x] = find(top[x]);
}
int upp(int x, int y) {
	return (x + y - 1) / y;
}
signed main() {
	cin >> n >> m;
	for (int i = 2, x; i <= n; i++) {
		scanf("%lld", &x);
		fa[i] = x;
		v[x].push_back(i);
	}
	for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
	for (int i = 1; i <= m; i++) {
		scanf("%lld%lld", &ask[i].u, &ask[i].x);
		ask[i].id = i;
	}
	sort(ask + 1, ask + 1 + m);
	int low = ask[1].x;
	for (int i = 1; i <= n; i++) a[i] += low;
	for (int i = 1; i <= m; i++) ask[i].x -= low;
	dfs(1);
	for (int i = 1; i <= n; i++) {
		q.push({i, a[i], 0});
		b[i] = -a[i];
		cnt[i] = 1, sum[i] = -a[i];
	}
	for (int i = 1; i <= m; i++) {
		while (q.size()) {
			tt tmp = q.top();
			tmp.x = -tmp.x;
			if (tmp.x > ask[i].x) break;
			q.pop();
			int u = tmp.u;
			if (find(u) != u) continue;
			int ss = query(0, ed[u]) - query(0, st[u] - 1), cc = query(1, ed[u]) - query(1, st[u] - 1);
			int tp = find(fa[u]);
			add(0, st[fa[u]], ss), add(1, st[fa[u]], cc);
			sum[tp] += ss, cnt[tp] += cc;
			top[tmp.u] = tp;
			if (tp != 0) {
				int ts = query(0, ed[tp]) - query(0, st[tp] - 1), tc = query(1, ed[tp]) - query(1, st[tp] - 1);
				add(0, st[fa[tp]], -ss), add(1, st[fa[tp]], -cc);
				b[tp] = upp(-ts, tc);
				q.push({tp, -upp(-ts, tc), 0});
			}
		}
		int ss = query(0, ed[ask[i].u]) - query(0, st[ask[i].u] - 1), cc = query(1, ed[ask[i].u]) - query(1, st[ask[i].u] - 1);
		ans[ask[i].id] = ss + cc * ask[i].x;
	}
	for (int i = 1; i <= m; i++) {
		printf("%lld\n", ans[i]);
	}
}
原文