Luogu P2982 [USACO10FEB]慢下来Slowing down

题目链接:传送门

读了好几遍题
没看到“粮仓在一号牧场”
所以没读懂卡了好久
意思就是一头牛走到自己的位置后
再有其他牛走过时
这头其他牛的答案会+1
树剖单点修改+询问一条链就好了

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define A 300010
#define B 2010

using namespace std;
typedef long long ll;
namespace Seg {
	struct node {
		int l, r, w, f;
	}tree[A];
	void build(int k, int l, int r) {
		tree[k].l = l; tree[k].r = r; tree[k].w = 0;
		if (l == r) return;
		int m = (l + r) >> 1;
		build(k << 1, l, m);
		build(k << 1 | 1, m + 1, r);
	}
	void down(int k) {
		tree[k << 1].f += tree[k].f;
		tree[k << 1 | 1].f += tree[k].f;
		tree[k << 1].w += (tree[k << 1].r - tree[k << 1].l + 1) * tree[k].f;
		tree[k << 1 | 1].w += (tree[k << 1 | 1].r - tree[k << 1 | 1].l + 1) * tree[k].f;
		tree[k].f = 0;
	}
	void change(int k, int pos) {
		if (tree[k].l == tree[k].r) {
			tree[k].w++;
			tree[k].f++;
			return;
		}
		if (tree[k].f) down(k);
		int m = (tree[k].l + tree[k].r) >> 1;
		if (pos <= m) change(k << 1, pos);
		else change(k << 1 | 1, pos);
		tree[k].w = tree[k << 1].w + tree[k << 1 | 1].w;
	}
	int ask(int k, int l, int r) {
		if (tree[k].l >= l and tree[k].r <= r) return tree[k].w;
		int m = (tree[k].l + tree[k].r) >> 1, ans = 0;
		if (tree[k].f) down(k);
		if (l <= m) ans += ask(k << 1, l, r);
		if (r > m) ans += ask(k << 1 | 1, l, r);
		return ans;
	}
};
int dfn[A], dep[A], fa[A], top[A], son[A], siz[A], cnt, pre[A];
namespace Cut {
	struct node {
		int next, to;
	}e[A];
	int head[A], num;
	void add(int fr, int to) {
		e[++num].next = head[fr];
		e[num].to = to;
		head[fr] = num;
	}
	void prepare(int fr) {
		siz[fr] = 1;
		for (int i = head[fr]; i; i = e[i].next) {
			int ca = e[i].to;
			if (ca == fa[fr]) continue;
			fa[ca] = fr;
			dep[ca] = dep[fr] + 1;
			prepare(ca);
			siz[fr] += siz[ca];
			if (siz[ca] > siz[son[fr]]) son[fr] = ca;
		}
	}
	void dfs(int fr, int tp) {
		dfn[fr] = ++cnt, pre[cnt] = fr, top[fr] = tp;
		if (!son[fr]) return;
		dfs(son[fr], tp);
		for (int i = head[fr]; i; i = e[i].next) {
			int ca = e[i].to;
			if (ca == fa[fr] or ca == son[fr]) continue;
			dfs(ca, ca);
		}
	}
	int ask(int x, int y, int ans = 0) {
		while (top[x] != top[y]) {
			if (dep[top[x]] < dep[top[y]]) swap(x, y);
			ans += Seg::ask(1, dfn[top[x]], dfn[x]);
			x = fa[top[x]];
		}
		if (dep[x] > dep[y]) swap(x, y);
		ans += Seg::ask(1, dfn[x], dfn[y]);
		return ans;
	}
}
int n, a, b;

int main(int argc, char const *argv[]) {
	cin >> n;
	for (int i = 2; i <= n; i++) {
		cin >> a >> b;
		Cut::add(a, b); Cut::add(b, a);
	}
	Cut::prepare(1); Cut::dfs(1, 1); Seg::build(1, 1, n);
	for (int i = 1; i <= n; i++) {
		cin >> a;
		cout << Cut::ask(1, a) << endl;
		Seg::change(1, dfn[a]);
	}
	return 0;
}

你可能感兴趣的:(线段树,树链剖分,Luogu)