loj2011「SCOI2015」情报传递

终于见到了一道水题
一眼看过去就是主席树
因为修改很麻烦,所以我们直接预处理一下
假设士兵开始执行任务的时间是ai,现在询问的时间是t,限定是c,那么求的就是满足 a i < = j − c − 1 a_i<=j-c-1 ai<=jc1的i的个数
然后就把树上的每一个节点建一条链,然后将他的父亲合并下来,询问的时候计算[1,j-c-1]的个数就行了

#include 
#include 
#include 
#include 
#include 
using namespace std;
template<typename T>inline void read(T &x) {
	x = 0; int f = 0; char s = getchar();
	while (!isdigit(s)) f |= s=='-', s = getchar();
	while ( isdigit(s)) x = x * 10 + s - 48, s = getchar();
	x = f ? -x : x;
}
int ss = 0, buf[31];
template<typename T>inline void print(T x) {
	if (x < 0) putchar('-'), x = -x;
	do {buf[++ss] = int(x % 10); x /= 10;} while(x);
	while (ss) putchar(buf[ss--] + '0');
}
const int N = 2e5 + 6;
struct trnode {
	int lc, rc, c;
}t[2600000]; int cnt, a[N];

int rt[N], dep[N], fa[N][25], n, m, root;
struct node {int opt, x, y, z;} cc[N];
struct edge { int y, nxt; } e[N]; int tot, last[N];
void ins (int x, int y) {
	tot++; e[tot].y = y; 
	e[tot].nxt = last[x]; last[x] = tot;
}

void Link(int &u, int l, int r, int p) {
	if (!u) u = ++cnt;
	t[u].c++;
	if (l == r) return;
	int mid = (l + r) >> 1;
	if (p <= mid) Link(t[u].lc, l, mid, p);
	else Link(t[u].rc, mid + 1, r, p);
}

void Merge(int &u1, int u2) {
	if (!u1) { u1 = u2; return;}
	if (!u2) return;
	t[u1].c += t[u2].c;
	Merge(t[u1].lc, t[u2].lc);
	Merge(t[u1].rc, t[u2].rc);
}

int Calc(int u1, int u2, int u3, int u4, int l, int r, int L, int R) {
	if (L <= l && r <= R)
		return t[u1].c + t[u2].c - t[u3].c - t[u4].c;
	int mid = (l + r) >> 1, sum = 0;
	if (L <= mid) sum += Calc(t[u1].lc, t[u2].lc, t[u3].lc, t[u4].lc, l, mid, L, R);
	if (mid < R) sum += Calc(t[u1].rc, t[u2].rc, t[u3].rc, t[u4].rc, mid + 1, r, L, R);
	return sum;
}

void Dfs(int x) {
	Merge(rt[x], rt[fa[x][0]]);
	dep[x] = dep[fa[x][0]] + 1;
	for (int i = 1; (1 << i) < dep[x]; i++)
		fa[x][i] = fa[fa[x][i - 1]][i - 1];
	for (int k = last[x]; k; k = e[k].nxt) Dfs(e[k].y);
}

int Lca(int x, int y) {
	if (dep[x] < dep[y]) swap(x, y);
	for (int i = 20; i >= 0; i--)
		if ((1 << i) <= dep[x] - dep[y])
			x = fa[x][i];
	if (x == y) return x;
	for (int i = 20; i >= 0; i--)
		if (fa[x][i] != fa[y][i])
			x = fa[x][i], y = fa[y][i];
	return fa[x][0];
}

int main() {
	read(n);
	for (int i = 1; i <= n; i++) {
		read(fa[i][0]);
		if (!fa[i][0]) root = i;
		else ins(fa[i][0], i);
	}
	read(m); int tt = 0;
	for (int i = 1; i <= n; i++) a[i] = m;
	for (int i = 1; i <= m; i++) {
		read(cc[i].opt);
		if (cc[i].opt == 1) {
			cc[++tt].opt = i;
			read(cc[tt].x), read(cc[tt].y), read(cc[tt].z);
		}
		else { read(cc[i].x); a[cc[i].x] = i; }
	}
	for (int i = 1; i <= n; i++) 
		Link(rt[i], 1, m, a[i]);
	Dfs(root);
	for (int i = 1; i <= tt; i++) {
		int lca = Lca(cc[i].x, cc[i].y);
		print(dep[cc[i].x] + dep[cc[i].y] - dep[lca] - dep[fa[lca][0]]); putchar(' ');
		int limit = cc[i].opt - cc[i].z - 1;
		if (limit < 1) putchar('0');
		else print(Calc(rt[cc[i].x], rt[cc[i].y], rt[lca], rt[fa[lca][0]], 1, m, 1, limit));
		puts("");
	}
	return 0;
}

你可能感兴趣的:(loj,各省省选)