「CF1295」Permutation Separation

#1295E. Permutation Separation

Summarize

给定一个 $1-n$ 的排列。将该排列划分为非空的前后缀,要求在两个集合间移动一些元素,其中移动第 $i$ 个元素的代价为 $a_i$,使得在前缀集合中的所有元素均小于后缀集合中的任意元素。

$n\le 2e5,a_i\le 1e9$

Solution

记变量 $val$ 表示将 $1-val$ 移至前缀集合,将 $(val+1)-n$ 移至后缀集合。记 $t[pos]$ 表示将排列划分为 $1-pos,(pos+1)-n$ 所花费的代价。

考虑当 $val$ 增加 $1$ 时,$t$ 数组的变化,可以用线段树维护。

Note

竟然一遍写对线段树我好开心 qwq

如果遇到障碍,可以转化值域定义再次尝试,重新确定枚举对象。

Code

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;
}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×