1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <bits/stdc++.h> using namespace std; #define lson(u) node[u].l #define rson(u) node[u].r #define val(u) node[u].val #define tag(u) node[u].tag typedef long long ll;
const ll INF = 1e16; const int MAXN = 2e5 + 5;
struct Node { int l, r; ll val, tag; } node[MAXN << 1]; int cnt = 0, R = 0;
int n, p[MAXN], b[MAXN]; ll a[MAXN], t[MAXN];
void pushup(int u) { val(u) = min(val(lson(u)), val(rson(u))); }
void pushdown(int u) { if (tag(u)) { val(lson(u)) += tag(u); val(rson(u)) += tag(u); tag(lson(u)) += tag(u); tag(rson(u)) += tag(u); tag(u) = 0; } }
void build(int& u, int l, int r) { u = ++cnt; if (l == r) { val(u) = t[l]; return; } int mid = (l + r) >> 1; build(lson(u), l, mid), build(rson(u), mid + 1, r); pushup(u); }
void modify(int u, int l, int r, int ql, int qr, ll val) { if (ql <= l && r <= qr) { tag(u) += val; val(u) += val; return; } pushdown(u); int mid = (l + r) >> 1; if (ql <= mid) modify(lson(u), l, mid, ql, qr, val); if (mid < qr) modify(rson(u), mid + 1, r, ql, qr, val); pushup(u); }
int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &p[i]), b[p[i]] = i; for (int i = 1; i <= n; ++i) scanf("%I64d", &a[i]); for (int i = 1; i <= n - 1; ++i) t[i] = t[i - 1] + a[i]; ll ans = t[1]; build(R, 1, n - 1); for (int i = 1; i <= n; ++i) { int pos = b[i]; if (1 <= pos - 1) modify(R, 1, n - 1, 1, pos - 1, a[pos]); if (pos <= n - 1) modify(R, 1, n - 1, pos, n - 1, -a[pos]); ans = min(ans, val(R)); } printf("%I64d", ans); return 0; }
|