针对范围最大查询优化分段树?

时间:2015-07-18 11:45:04

标签: c optimization segment-tree range-query

所以我需要一些帮助。我最近开始在codechef上做中等水平的问题,因此我得到了很多TLE。

所以基本上问题是找到问题中给出的多个最大范围查询的总和。给出了初始范围,下一个值是通过问题中给出的公式计算的。

我使用了段树来解决问题,但我一直在为某些子任务获得TLE。请帮我优化这段代码。

问题链接 - https://www.codechef.com/problems/FRMQ

//solved using segment tree
#include <stdio.h>
#define gc getchar_unlocked
inline int read_int()  //fast input function 
{
    char c = gc();
    while(c<'0' || c>'9') 
        c = gc();
    int ret = 0;
    while(c>='0' && c<='9') 
    {
        ret = 10 * ret + c - '0';
        c = gc();
    }
    return ret;
}
int min(int a,int b)
{
    return (a<b?a:b);
}
int max(int a,int b)
{
    return (a>b?a:b);
}
void construct(int a[],int tree[],int low,int high,int pos)  //constructs 
{                                          //the segment tree by recursion
    if(low==high)
    {
        tree[pos]=a[low];
        return;
    }
    int mid=(low+high)>>1;
    construct(a,tree,low,mid,(pos<<1)+1);
    construct(a,tree,mid+1,high,(pos<<1)+2);
    tree[pos]=max(tree[(pos<<1)+1],tree[(pos<<1)+2]);
}
int query(int tree[],int qlow,int qhigh,int low,int high,int pos)
{   //function finds the maximum value using the 3 cases
    if(qlow<=low && qhigh>=high)
        return tree[pos];            //total overlap
    if(qlow>high || qhigh<low)
        return -1;                   //no overlap
    int mid=(low+high)>>1;           //else partial overlap
    return max(query(tree,qlow,qhigh,low,mid,(pos<<1)+1),query(tree,qlow,qhigh,mid+1,high,(pos<<1)+2));
}
int main()
{
    int n,m,i,temp,x,y,ql,qh;
    long long int sum;
    n=read_int();
    int a[n];
    for(i=0;i<n;i++)
        a[i]=read_int();
    i=1;
    while(temp<n)       //find size of tree
    {
        temp=1<<i;
        i++;
    }
    int size=(temp<<1)-1;
    int tree[size];
    construct(a,tree,0,n-1,0);
    m=read_int();
    x=read_int();
    y=read_int();
    sum=0;
    for(i=0;i<m;i++)
    {
        ql=min(x,y);
        qh=max(x,y);
        sum+=query(tree,ql,qh,0,n-1,0);
        x=(x+7)%(n-1);     //formula to generate the range of query
        y=(y+11)%n;
    }
    printf("%lld",sum);
    return 0;
}

2 个答案:

答案 0 :(得分:0)

几点说明:

  1. 使用快速IO例程非常棒。
  2. 确保您不使用模运算,因为它非常慢。要计算余数,只需从数字中减去N,直到它变得小于N.这样可以更快地运行。
  3. 您的算法在O((M + N)* log N)时间内工作,这不是最佳的。对于静态RMQ问题,使用sparse table更好更简单。它需要O(N log N)空间和O(M + N log N)时间。

答案 1 :(得分:0)

好吧,我想要获得100分你需要使用稀疏表。

我尝试优化您的代码https://www.codechef.com/viewsolution/7535957(运行时间从0.11秒减少到0.06秒) 但仍然不足以通过子任务3 ..

相关问题