思路:
转化为RMQ。
实现:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 const int MAXN = 100005; 6 const int INF = 0x3f3f3f3f; 7 8 int a[MAXN], tree[MAXN * 4], n, m, sum[MAXN]; 9 10 void build(int num, int l, int r) 11 { 12 if (l == r) { tree[num] = a[l]; return; } 13 int m = l + r >> 1; 14 build(num * 2, l, m); 15 build(num * 2 + 1, m + 1, r); 16 tree[num] = max(tree[num * 2], tree[num * 2 + 1]); 17 } 18 19 int query(int num, int l, int r, int x, int y) 20 { 21 if (x <= l && y >= r) return tree[num]; 22 int ans = -INF, m = l + r >> 1; 23 if (x <= m) ans = max(ans, query(num * 2, l, m, x, y)); 24 if (y >= m + 1) ans = max(ans, query(num * 2 + 1, m + 1, r, x, y)); 25 return ans; 26 } 27 28 int main() 29 { 30 while (scanf("%d", &n), n) 31 { 32 memset(a, 0, sizeof a); 33 memset(sum, 0, sizeof sum); 34 scanf("%d", &m); 35 int last = -INF, tmp, now = 0; 36 for (int i = 1; i <= n; i++) 37 { 38 scanf("%d", &tmp); 39 if (tmp == last) a[now]++; 40 else last = tmp, a[++now]++; 41 } 42 build(1, 1, now); 43 for (int i = 1; i <= now; i++) sum[i] = sum[i - 1] + a[i]; 44 int l, r; 45 for (int i = 0; i < m; i++) 46 { 47 scanf("%d %d", &l, &r); 48 int ls = lower_bound(sum, sum + now + 1, l) - sum; 49 int rs = lower_bound(sum, sum + now + 1, r) - sum; 50 int ans = -1; 51 if (ls == rs) ans = r - l + 1; 52 else 53 { 54 ans = max(sum[ls] - l + 1, r - sum[rs - 1]); 55 if (rs - ls > 1) ans = max(ans, query(1, 1, now, ls + 1, rs - 1)); 56 } 57 printf("%d\n", ans); 58 } 59 } 60 return 0; 61 }
原文地址:https://www.cnblogs.com/wangyiming/p/8455107.html
时间: 2024-11-09 02:44:38