您的位置:首页 > 其它

hdu 1806(线段树区间合并)

2016-04-04 13:03 465 查看

Frequent values

Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1476 Accepted Submission(s): 541


[align=left]Problem Description[/align]
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 .

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each query, print one line with one integer: The number of occurrences of the most frequent value within the given range.

[align=left]Sample Input[/align]

10 3
-1 -1 1 1 1 1 3 10 10 10
2 3
1 10
5 10
0

[align=left]Sample Output[/align]
1
4
3

上一题的弱化版 http://www.cnblogs.com/liyinggang/p/5351694.html
有个RMQ的解法,利用游标编码,代码简单,但是理解可能复杂点

#include<iostream>
#include<cstdio>
#include<algorithm>
#define N 100005
using namespace std;

int a
;
struct Tree{
int l,r;
int lv,rv,mv;
}tree[4*N];

void PushUp(int l,int r,int idx){
tree[idx].lv = tree[idx<<1].lv;
tree[idx].rv = tree[idx<<1|1].rv;
tree[idx].mv = max(tree[idx<<1].mv,tree[idx<<1|1].mv);
int mid = (l+r)>>1;
int len = r- l+1;
if(a[mid]==a[mid+1]){
if(tree[idx].lv==len-(len>>1)) tree[idx].lv+=tree[idx<<1|1].lv;
if(tree[idx].rv==(len>>1)) tree[idx].rv+=tree[idx<<1].rv;
tree[idx].mv = max(tree[idx].mv,tree[idx<<1].rv+tree[idx<<1|1].lv);
}
}
void build(int l,int r,int idx){
tree[idx].l = l;
tree[idx].r = r;
if(l==r){
tree[idx].lv = tree[idx].rv = tree[idx].mv = 1;
return;
}
int mid = (l+r)>>1;
build(l,mid,idx<<1);
build(mid+1,r,idx<<1|1);
PushUp(l,r,idx);
}
int query(int l,int r,int idx){
if(tree[idx].l>=l&&tree[idx].r<=r){
return tree[idx].mv;
}
int mid = (tree[idx].l+tree[idx].r)>>1;
int ans = 0;
if(l<=mid) ans = max(ans,query(l,r,idx<<1));
if(r>mid) ans=max(ans,query(l,r,idx<<1|1));
if(a[mid]==a[mid+1]){
ans = max(ans,min(mid-l+1,tree[idx<<1].rv)+min(r-mid,tree[idx<<1|1].lv));
}
return ans;
}
int main()
{
int n,m;
while(scanf("%d",&n)!=EOF,n){
scanf("%d",&m);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
build(1,n,1);
while(m--){
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",query(a,b,1));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: