HDU1754 I Hate It

题面:http://acm.hdu.edu.cn/showproblem.php?pid=1754

题意

区间最大值查询,单点修改问题。线段树&分块等模板题

解法

分块或者线段树

分块例程

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
#include<bits/stdc++.h>
using namespace std;
const int maxm = 2e3 + 10;
const int maxn = 2e5 + 10;
int l[maxm], r[maxm], b[maxn];
int a[maxn], belong[maxn];
int query(int x, int y)
{
int res = 0;
for(int i = x; i <= min(y, r[belong[x]]); i++)
res = max(res, a[i]);
if(belong[x] == belong[y])
return res;
for(int i = belong[x] + 1; i < belong[y]; i++)
res = max(res, b[i]);
for(int i = l[belong[y]]; i <= y; i++)
res = max(res, a[i]);
return res;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
while(cin >> n >> m)
{
memset(b, 0, sizeof(b));
int block = sqrt(n);
int num = n / block;
if(n % block)num++;
for(int i = 1; i <= n; i++)
belong[i] = (i - 1) / block + 1;
for(int i = 1; i <= num; i++)
{
l[i] = (i - 1) * block + 1;
r[i] = i * block;//处理每块的左右边界;
}
r[num] = n;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
b[belong[i]] = max(b[belong[i]], a[i]);
}
while(m--)
{
char c; int x, y;
cin >> c >> x >> y;
if(c == 'Q')
cout << query(x, y) << endl;
else{
a[x] = y;
b[belong[x]] = max(b[belong[x]], y);
}
}
}
}

线段树例程

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
#include<bits/stdc++.h>
using namespace std;
const int maxm = 5e3 + 10;
const int maxn = 1e6 + 10;
int a[maxn];
int n, dat[2 * maxn - 1];
void init(int N)
{
n = 1;
while(n < N)
n <<= 1;
for(int i = 0; i < 2 * n - 1; i++)
dat[i] = INT_MIN;
}
void update(int k, int a)
{
k += n - 1;
dat[k] = a;
while(k > 0)
{
k = (k - 1) / 2;
dat[k] = max(dat[k * 2 + 1], dat[k * 2 + 2]);
}
}
int query(int a, int b, int l, int r, int k)
{
if(a >= r || b <= l)
return INT_MIN;
if(a <= l && b >= r)
return dat[k];
return max(query(a, b, l, (l + r) / 2, k * 2 + 1), query(a, b, (l + r) / 2, r, k * 2 + 2));
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int N, m;
string c;
while(cin >> N >> m)
{
init(N);
for(int i = 0; i < N; i++)
{
int t; cin >> t;
update(i, t);
}
while(m--)
{
string q; int l, r;
cin >> q >> l >> r;
if(q[0] == 'Q')
cout << query(l - 1, r, 0, n, 0) << endl;
else
update(l - 1, r);
}

}
return 0;
}