想试试指针的写法
struct node {
node *ch[2];
int key;
node(){
key = 0;
ch[0] = ch[1] = nullptr;
}
node(node *_node){
key = _node -> key;
ch[0] = _node -> ch[0], ch[1] = _node -> ch[1];
}
};
然后就在#2 MLE了 可能因为本人比较菜,也没想到进一步优化的办法 代码在下方,请大佬指教
// Problem: P3919 【模板】可持久化线段树 1(可持久化数组)
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3919
// Memory Limit: 500 MB
// Time Limit: 1500 ms
//
// Powered by CP Editor (https://cpeditor.org)
// created on Laptop of Lucian Xu
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <queue>
#include <utility>
#include <unordered_map>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<int, LL> PIL;
#define rep(i, l, r) for(auto i = (l); i <= (r); i++)
#define per(i, r, l) for(auto i = (r); i >= (l); i--)
#define ff first
#define ss second
#define m_p make_pair
#define p_b push_back
#define endl '\n'
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
const int N = 1e6+10;
const int mod = 998244353;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
const double eps = 1e-6;
int n, m, k, x, vi, op, a[N];
struct node {
node *ch[2];
int key;
node(){
key = 0;
ch[0] = ch[1] = nullptr;
}
node(node *_node){
key = _node -> key;
ch[0] = _node -> ch[0], ch[1] = _node -> ch[1];
}
};
struct segment_tree{
node *root[N];
node *build(int l, int r){
node *new_node; new_node = new node();
if(l == r){
new_node -> key = a[l];
return new_node;
}
int mid = (l + r) >> 1;
new_node -> ch[0] = build(l, mid);
new_node -> ch[1] = build(mid + 1, r);
return new_node;
}
// a[k] 改成 x //
node *modify(node *p, int l, int r, int k, int x){
node *new_node;
new_node = new node(p);
if(l == r){
new_node -> key = x;
return new_node;
}
int mid = (l + r) >> 1;
if(k <= mid) new_node -> ch[0] = modify(new_node -> ch[0], l, mid, k, x);
else new_node -> ch[1] = modify(new_node -> ch[1], mid + 1, r, k, x);
return new_node;
}
// 询问 p 为根节点的版本的 a[k] //
int query(node *p, int l, int r, int k){
if(l == r){
return p -> key;
}
int mid = (l + r) >> 1;
if(k <= mid) return query(p -> ch[0], l, mid, k);
else return query(p -> ch[1], mid + 1, r, k);
}
};
segment_tree tr;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
rep(i, 1, n) cin >> a[i];
tr.root[0] = tr.build(1, n);
rep(i, 1, m){
cin >> vi >> op;
if(op == 1){
cin >> k >> x;
tr.root[i] = tr.modify(tr.root[vi], 1, n, k, x);
}
else{
cin >> k;
tr.root[i] = tr.root[vi];
cout << tr.query(tr.root[vi], 1, n, k) << endl;
}
}
return 0;
}