TZOJ1114: Frequent values
描述
You are given a sequence of n integers a1 , a2 , … , an in non-decreasing order. In addition to that, you are given several queries consisting of indices i and j (1 ≤ i ≤ j ≤ n). For each query, determine the most frequent value among the integers ai , … , aj.
输入
The input consists of several test cases. Each test case starts with a line containing two integers n and q (1 ≤ n, q ≤ 100000). The next line contains n integers a1 , … , an (-100000 ≤ ai ≤ 100000, for each i ∈ {1, …, n}) separated by spaces. You can assume that for each i ∈ {1, …, n-1}: ai ≤ ai+1. The following q lines contain one query each, consisting of two integers i and j (1 ≤ i ≤ j ≤ n), which indicate the boundary indices for the query.
The last test case is followed by a line containing a single 0.
输出
For each query, print one line with one integer: The number of occurrences of the most frequent value within the given range.
样例输入
10 3
-1 -1 1 1 1 1 3 10 10 10
2 3
1 10
5 10
0
样例输出
1
4
3
解题思路
题目要求区间最多连续相同数的个数,显然这是一个RMQ类的题目,可以使用线段树或者ST表求解,这里使用线段树。参考1、参考2。
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define lrt rt << 1
#define rrt rt << 1 | 1
#define lson l, mid, lrt
#define rson mid + 1, r, rrt
#define inf 0x3f3f3f3f
#define IOS ios::sync_with_stdio(0), cin.tie(0)
const ll N = 1e5 * 1 + 5;
inline ll read() {
ll x=0,f=1;char c=getchar();
while (!isdigit(c)) {if(c=='-')f=-1;c=getchar();}
while (isdigit(c)) {x=(x<<3)+(x<<1)+(c^48);c=getchar();}
return x*f;
}
struct node {
ll mx, lmx, rmx;
}tr[N << 2];
//mx表示当前区间最多连续相同数的个数,lmx是从最左边数起的,rmx是从最右边数起的
ll n, q, a[N];
void pu(ll l, ll r, ll rt) {
tr[rt].lmx = tr[lrt].lmx;//根的左最值初始化为左儿子的左最值
tr[rt].rmx = tr[rrt].rmx;//根的右最值初始化为右儿子的右最值
tr[rt].mx = max(tr[lrt].mx, tr[rrt].mx);
ll mid = l + r >> 1;
ll m = r - l + 1;//区间长度
//当左右可以延伸时
if(a[mid] == a[mid + 1]) {
//如果根的左最值为当前左区间长度,根的左最值加上右子区间的左最值,表示延伸
if(tr[rt].lmx == m - (m >> 1)) tr[rt].lmx += tr[rrt].lmx;
if(tr[rt].rmx == (m >> 1)) tr[rt].rmx += tr[lrt].rmx;//同理
tr[rt].mx = max(tr[rt].mx, tr[lrt].rmx + tr[rrt].lmx);//延伸合并取最大
}
}
void bd(ll l, ll r, ll rt) {
if(l == r) {
tr[rt].mx = tr[rt].lmx = tr[rt].rmx = 1;
return;
}
ll mid = l + r >> 1;
bd(lson);bd(rson);pu(l, r, rt);
}
ll qy(ll L, ll R, ll l, ll r, ll rt) {
if (L <= l && R >= r) return tr[rt].mx;
ll mid = l + r >> 1;
ll ans = 0;
if(L <= mid) ans = max(ans, qy(L, R, lson));
if(R > mid) ans = max(ans, qy(L, R, rson));
//当左右可以延伸时
if (a[mid] == a[mid + 1]) {
//求最大长度
//当前左区间长度与左子区间右最值取小,加上,当前右区间长度与右子区间左最值取小,与ans比较取大
ans = max(ans, min(mid - L + 1, tr[lrt].rmx) + min(R - mid, tr[rrt].lmx));
}
return ans;
}
void solve() {
while (~scanf("%lld", &n), n) {
q = read();
for (int i = 1; i <= n; ++i) {
a[i] = read();
}
bd(1, n, 1);
while (q--) {
ll x, y; x = read(); y = read();
cout << qy(x, y, 1, n, 1) << '\n';
}
}
}
int main( ){
// IOS;
// ll t; cin >> t;
ll t = 1;
while (t--) solve();
return 0;
}