NOIP2012 Day2 T2(线段树/二分+前缀和+离线)

线段树做法:
裸模板,维护区间增加区间最小值,但是常数大容易T

二分+前缀和做法:
每次二分一个通过申请的个数,然后暴力前缀和判断,复杂度与线段树一样,但是常数小

线段树做法:

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
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
#define db double
using namespace std;
const int MAXN = 1000000 + 5;
int n, m, ri[MAXN];
#define lc (o << 1)
#define rc ((o << 1) | 1)
#define M ((l + r) >> 1)
int minv[MAXN * 4], addv[MAXN * 4];
void pushup(int o) {
minv[o] = min(minv[lc], minv[rc]);
}
void pushdown(int o) {
if (addv[o]) {
addv[lc] += addv[o], addv[rc] += addv[o];
minv[lc] += addv[o], minv[rc] += addv[o];
addv[o] = 0;
}
}
void build(int o, int l, int r) {
if (l == r) minv[o] = ri[l]; else build(lc, l, M), build(rc, M + 1, r), pushup(o);
}
void update(int o, int l, int r, int x, int y, int v) {
if (x <= l && r <= y) {
minv[o] += v, addv[o] += v;
return ;
}
pushdown(o);
if (x <= M) update(lc, l, M, x, y, v);
if (M < y) update(rc, M + 1, r, x, y, v);
pushup(o);
}
int query(int o, int l, int r, int x, int y) {
int ret = 2000000000;
if (x <= l && r <= y) {
return minv[o];
}
pushdown(o);
if (x <= M) ret = min(ret, query(lc, l, M, x, y));
if (M < y) ret = min(ret, query(rc, M + 1, r, x, y));
pushup(o);
return ret;
}
void clean() {
ms(addv, 0);
}
void solve() {
clean();
for (int i = 1; i <= n; i++) scanf("%d", &ri[i]);
build(1, 1, n);
for (int i = 1; i <= m; i++) {
int di, si, ti;
scanf("%d%d%d", &di, &si, &ti);
int ret = query(1, 1, n, si, ti);
if (ret < di) {
printf("-1\n%d\n", i);
return ;
}
update(1, 1, n, si, ti, -di);
}
printf("0\n");
}
int main() {
scanf("%d%d", &n, &m), solve();
return 0;
}

二分+前缀和做法:

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
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
#define db double
using namespace std;
const int MAXN = 1000000 + 5;
int n, m, ri[MAXN];
int di[MAXN], si[MAXN], ti[MAXN];
int ci[MAXN];
bool check(int x) {
for (int i = 0; i <= n + 1; i++) ci[i] = 0;
for (int i = 1; i <= x; i++) ci[si[i]] += di[i], ci[ti[i] + 1] -= di[i];
for (int i = 1; i <= n + 1; i++) {
ci[i] += ci[i - 1];
if (ci[i] > ri[i]) return false;
}
return true;
}
void clean() {}
void solve() {
clean();
for (int i = 1; i <= n; i++) scanf("%d", &ri[i]);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &di[i], &si[i], &ti[i]);
}
int ans = 0, l = 0, r = m + 1;
while (l < r) {
int mid = (l + r) / 2;
if (check(mid)) l = mid + 1, ans = mid; else r = mid;
}
if (ans == m) printf("0\n"); else printf("-1\n%d\n", ans + 1);
}
int main() {
scanf("%d%d", &n, &m), solve();
return 0;
}

------ 本文结束 ------