hdu 1806(线段树区间合并)

Frequent values

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


Problem Description
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 .

 

 

Input
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.

 

 

Output
For each query, print one line with one integer: The number of occurrences of the most frequent value within the given range.
 

 

Sample Input
10 3 -1 -1 1 1 1 1 3 10 10 10 2 3 1 10 5 10 0
 

 

Sample Output
1 4 3
 
有个RMQ的解法,利用游标编码,代码简单,但是理解可能复杂点
#include<iostream>
#include<cstdio>
#include<algorithm>
#define N 100005
using namespace std;

int a[N];
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;
}

 

 
posted @ 2016-04-04 13:03  樱花庄的龙之介大人  阅读(294)  评论(0编辑  收藏  举报