#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define MP make_pair
typedef long long LL;
typedef unsigned long long ull;
typedef pair<LL, int> pli;
typedef pair<int, int> pii;
typedef pair<ull, int> pui;
const int V = 2e3 + 7, N = 3e4 + 7;
template<typename T>
T& Fmin(T &x, T y) { return x = x < y ? x : y; }
template<typename T>
T& Fmax(T &x, T y) { return x = y < x ? x : y; }
LL read() {
char c = getchar(); LL x = 0, p = 1;
while ((c < '0' || c > '9') && c != '-') c = getchar();
if (c == '-') p = -1, c = getchar();
while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
return x * p;
}
vector<int> e[N];
vector<pair<int, int>> q[N];
int n, Q, rt[N], ans[N], tot, cnt;
struct Thing { int w, v; };
struct Tag { int op; Thing x; Tag() { op = 0; } } lzy[N];
struct DP { int f[V]; void clear() { memset(f, 0, sizeof f); } };
DP operator + (DP x, Thing y) {
DP ans = x;
for (int i = V - 1; i >= y.w; i --)
Fmax(ans.f[i], ans.f[i - y.w] + y.v);
return ans;
}
struct Stack {
int tp; Thing sk[N]; DP val[N];
Stack () { tp = 0, val[0].clear(); }
void push(Thing x) {
tp ++, val[tp] = val[tp - 1] + (sk[tp] = x);
}
};
struct Deque {
Stack s, t; Thing tmp[N];
void push_front(Thing x) { s.push(x); }
void push_back(Thing x) { t.push(x); }
void pop_front() {
if (s.tp) return s.tp --, void();
int num = t.tp - 1;
for (int i = 1; i <= num; i ++) tmp[i] = t.sk[i + 1];
t.tp = 0;
int mid = num >> 1;
for (int i = mid; i >= 1; i --) s.push(tmp[i]);
for (int i = mid + 1; i <= num; i ++) t.push(tmp[i]);
}
void pop_back() {
if (t.tp) return t.tp --, void();
int num = s.tp - 1;
for (int i = 1; i <= num; i ++) tmp[i] = s.sk[s.tp - i + 1];
s.tp = 0;
int mid = num >> 1;
for (int i = mid; i >= 1; i --) s.push(tmp[i]);
for (int i = mid + 1; i <= num; i ++) t.push(tmp[i]);
}
Thing front() { return s.sk[s.tp]; }
Thing back() { return t.sk[t.tp]; }
int query(int x) {
DP f = s.val[s.tp], g = t.val[t.tp]; int ans = 0;
for (int i = 0; i <= x; i ++) Fmax(ans, f.f[i] + g.f[x - i]);
return ans;
}
} dq;
void dfs(int x) {
Thing tmp;
if (lzy[x].op == 1) dq.push_back(lzy[x].x);
if (lzy[x].op == 2) tmp = dq.front(), dq.pop_front();
for (auto i : q[x]) ans[i.se] = dq.query(i.fi);
for (int i : e[x]) dfs(i);
if (lzy[x].op == 1) dq.pop_back();
if (lzy[x].op == 2) dq.push_front(tmp);
}
int main() {
Q = read(), rt[n = 1] = tot = 1;
for (int i = 1, opt, x, p, t; i <= Q; i ++) {
opt = read(), x = read();
if (opt == 1) rt[++ n] = rt[x];
if (opt == 2) {
p = read(), t = read();
e[rt[x]].push_back(++ tot);
lzy[rt[x] = tot].op = 1;
lzy[tot].x = {p, t};
} if (opt == 3) {
e[rt[x]].push_back(++ tot);
lzy[rt[x] = tot].op = 2;
} if (opt == 4)
q[rt[x]].push_back(MP(read(), ++ cnt));
}
dfs(1);
for (int i = 1; i <= cnt; i ++) cout << ans[i] << '\n';
return 0;
}