线段树的应用
维护最大值
之前知道cin cout 会比scanf慢
但是没有遇到一道题是真正因为cin cout TLE的
这题是第一个 不用scanf就会TLE
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m;
struct tr {
int l, r, maxv;
tr() {
l = 0;
r = 0;
maxv = 0;
}
tr(int a, int b, int c) {
l = a; r = b; maxv = c;
}
}tre[4 * N];
int w[N];
int pushup(int u) {
tre[u].maxv = max(tre[u << 1].maxv, tre[u << 1 | 1].maxv);
}
void build(int u, int l, int r) {
if (l == r)
{
tre[u] = tr(l, r, w[r]);
}
else {
tre[u] = tr(l, r, 0);
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
//tre[u].maxv = max(tre[u << 1].maxv, tre[u << 1 | 1].maxv);
}
}
int query(int u, int l, int r) {
if (tre[u].l >= l && tre[u].r <= r)
return tre[u].maxv;
int mid = tre[u].l + tre[u].r >> 1;
int maxv = -2e9;
if (l <= mid)
maxv = query(u << 1, l, r);
if (r >= mid + 1)
maxv = max(maxv, query(u << 1 | 1, l, r));
return maxv;
}
int main()
{
// ios::sync_with_stdio(false);
//cin.tie(0);cout.tie(0);
//cin >> n >> m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
//cin>>w[i];
scanf("%d", &w[i]);
int l, r;
build(1, 1, n);
while (m--) {
//cin>>l>>r;
scanf("%d%d", &l, &r);
//cout << query(1, l, r) << endl;
printf("%d\n", query(1, l, r));
}
return 0;
}