HDU1754 I Hate It 发表于 2018-12-11 | 分类于 题解 | 字数统计: 548 | 阅读时长 ≈ 3 题面:http://acm.hdu.edu.cn/showproblem.php?pid=1754 题意区间最大值查询,单点修改问题。线段树&分块等模板题 解法分块或者线段树 分块例程1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#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); } } }} 线段树例程1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#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;}