我的代码为什么跑那么慢???
  • 板块题目总版
  • 楼主Beta_Theta
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/8/7 17:38
  • 上次更新2024/8/7 19:01:22
查看原帖
我的代码为什么跑那么慢???
965461
Beta_Theta楼主2024/8/7 17:38
#include<bits/stdc++.h>
using namespace std;
const int N = 1000025;
int n, m, x, tot, wc[N], dfs[N], sz[N], dep[N], top[N], fa[N], ans;
vector<int> g[N];
char op[25];
struct node {
	int l, r, len, x, lz;
} t[N * 4];
void dfs1(int u) {
	sz[u] = 1;
	for (int v : g[u]) {
		if (v == fa[u]) continue;
		dep[v] = dep[u] + 1;
		fa[v] = u;
		dfs1(v);
		sz[u] += sz[v];
		if (sz[v] > sz[wc[u]]) wc[u] = v;
	}
}
void dfs2(int u, int TOP) {
	dfs[u] = ++tot;
	top[u] = TOP;
	if (wc[u]) dfs2(wc[u], TOP);
	for (int v : g[u]) {
		if (v == fa[u] || v == wc[u]) continue;
		dfs2(v, v);
	}
}
void build(int u, int l, int r) {
	t[u].l = l, t[u].r = r, t[u].lz = -1;
	t[u].len = r - l + 1;
	if (l == r) return;
	int mid = l + r >> 1;
	build(u << 1, l, mid);
	build(u << 1 | 1, mid + 1, r);
}
void pushdown(int u) {
	t[u << 1].x = (t[u << 1].r - t[u << 1].l + 1) * t[u].lz;
	t[u << 1 | 1].x = (t[u << 1 | 1].r - t[u << 1 | 1].l + 1) * t[u].lz;
	t[u << 1].lz = t[u << 1 | 1].lz = t[u].lz;
	t[u].lz = -1;
}
void change(int u, int l, int r, int k) {
	if (l <= t[u].l && t[u].r <= r) {
		t[u].x = (t[u].r - t[u].l + 1) * k;
		t[u].lz = k;
		return;
	}
	if (t[u].lz != -1) pushdown(u);
	if (t[u << 1].r >= l) change(u << 1, l, r, k);
	if (t[u << 1 | 1].l <= r) change(u << 1 | 1, l, r, k);
	t[u].x = t[u << 1].x + t[u << 1 | 1].x;
}
void update(int x, int k) {
	while (top[x] != top[0]) {
		change(1, dfs[top[x]], dfs[x], k);
		x = fa[top[x]];
	}
	change(1, dfs[0], dfs[x], k);
}
int read() {
	int x = 0, w = 1;
	char c = getchar();
	while (c < '0' || c > '9') {
		if (c == '-') w = -1;
		c = getchar();
	}
	while (c >= '0' && c <= '9') {
		x = (x << 3) + (x << 1) + (c ^ 48);
		c = getchar();
	}
	return x * w;
}
void write(int x) {
	if (x < 0) {
		x = -x;
		putchar('-');
	}
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}
int main() {
	n = read();
	for (int i = 1; i < n; i++) {
		x = read();
		g[i].push_back(x);
		g[x].push_back(i);
	}
	dfs1(0);
	dfs2(0, -1);
	build(1, 1, n);
	m = read();
	while (m--) {
		scanf("%s", op);
		x = read();
		ans = t[1].x;
		if (op[0] == 'i') {
			update(x, 1);
		} else {
			change(1, dfs[x], dfs[x] + sz[x] - 1, 0);
		}
		ans = abs(t[1].x - ans);
		write(ans);
		putchar('\n');
	}
	return 0;
}

别人树剖解法跑得飞快,我的直接T了几个点

测评记录

2024/8/7 17:38
加载中...