您的位置:首页 > 产品设计 > UI/UE

poj 3368 Frequent values 线段树 离散化

2016-02-12 19:59 423 查看

题目

题目链接:http://poj.org/problem?id=3368

题目来源:群中有人问的。

简要题意:不递减序列,找到区间内数最多的出现次数。

题解

对数组进行离散化。

找到每个区间左右多出来的那两段长度是多少。

对于中间的数可以搞个线段树或者用RMQ来弄出值在某区间内出现的最大值。

于是可以在O(nlogn)O(n\log n)时间内求解。

具体的做法我是用预处理向左向右第一个与a[i]a[i]不同的数的位置。

然后记数塞入一个线段树。

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>

#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
// head
const int N = 1E5+5;;

int a
;
int nxt
;
int pre
;
int cnt
;

struct SegmentTree {
#define lson (rt<<1)
#define rson ((rt<<1)|1)
#define MID ((L+R)>>1)
#define lsonPara lson, L, MID
#define rsonPara rson, MID+1, R

int tree[N<<2];

void update(int rt) {
tree[rt] = max(tree[lson], tree[rson]);
}

void build(int rt, int L, int R) {
if (L == R) {
tree[rt] = cnt[L];
} else {
build(lsonPara);
build(rsonPara);
update(rt);
}
}

int query(int rt, int L, int R, int l, int r) {
if (r < L || l > R) return 0;
if (l <= L && r >= R) return tree[rt];
return max(query(lsonPara, l, r), query(rsonPara, l, r));
}
};

SegmentTree st;
int main() {
int n, q;
while (scanf("%d%d", &n, &q) == 2) {
int cur = 0, curv = 1e9;
for (int i = 1; i <= n; i++) {
scanf("%d", a+i);
if (a[i] != curv) curv = a[i], cur++;
a[i] = cur;
cnt[cur]++;
}
for (int i = 1; i <= n; i++) {
pre[i] = a[i]==a[i-1] ? pre[i-1] : i-1;
}
for (int i = n; i > 0; i--) {
nxt[i] = a[i]==a[i+1] ? nxt[i+1] : i+1;
}

st.build(1, 1, cur);
int ll, rr;
while (q--) {
scanf("%d%d", &ll, &rr);
int lr = min(nxt[ll]-1, rr);
int rl = max(pre[rr]+1, ll);
int ans = max(lr - ll + 1, rr - rl + 1);
if (lr+1 <= rl-1) ans = max(ans, st.query(1, 1, cur, a[lr+1], a[rl-1]));
printf("%d\n", ans);
}
memset(cnt, 0, sizeof cnt);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: