萌新刚学指针,#2和#12过不了,求助
查看原帖
萌新刚学指针,#2和#12过不了,求助
226841
Segtree297楼主2021/12/4 09:19

如题,用数组做时可以AC,BaiduFS说似乎要释放空间,不太明白怎么释放,在哪里释放,求助各位dalao((
以下是结果。 od5B40.png

以下是代码

#include <bits/stdc++.h>
#define N int(1e6+10)
using namespace std;

struct node {
	int value;
	node *ls;
	node *rs;
};
int n, m;
int a[N];
node *rt[N];

node *build(int l, int r) {
	node *pos = new node;
	if (l == r) {
		pos->value = a[l];
		pos->ls = NULL;
		pos->rs = NULL;
	} else {
		int mid = l + r >> 1;
		pos->value = 0;
		pos->ls = build(l, mid);
		pos->rs = build(mid + 1, r);
	}
	return pos;
}

node *update(int loc, int val, node *now, int l, int r) {
	node *pos = new node;
	if (l == r) {
		pos->value = val;
		pos->ls = NULL;
		pos->rs = NULL;
	} else {
		int mid = l + r >> 1;
		if (loc <= mid) {
			pos->ls = update(loc, val, now->ls, l, mid);
			pos->rs = now->rs;
		} else {
			pos->ls = now->ls;
			pos->rs = update(loc, val, now->rs, mid + 1, r);
		}
	}
	return pos;
}

int query(int loc, node *now, int l, int r) {
	if (l == r) {
		return now->value;
	} else {
		int mid = l + r >> 1;
		if (loc <= mid) {
			return query(loc, now->ls, l, mid);
		} else {
			return query(loc, now->rs, mid + 1, r);
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	rt[0] = build(1, n);
	int ver, opt, loc, val;
	for (int i = 1; i <= m; i++) {
		cin >> ver >> opt >> loc;
		if (opt == 1) {
			cin >> val;
			rt[i] = update(loc, val, rt[ver], 1, n);
		} else if (opt == 2) {
			rt[i] = rt[ver];
			cout << query(loc, rt[i], 1, n) << endl;
		}
	}
	return 0;
}

2021/12/4 09:19
加载中...