码迷,mamicode.com
首页 > 其他好文 > 详细

51Nod—1174 区间中最大的数 线段树模版

时间:2017-07-12 15:06:02      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:--   最大   int   blog   线段树   space   pre   帮助   pac   

在大佬们题解的帮助下算是看懂了线段树吧。。。在这mark下防一手转头就忘。

#include<iostream>
#include<stdio.h>
using namespace std;
struct ki
{
    int m,l,r;
}tree[40005];
int ans=-1,a[10005];
void build(int n,int l,int r)
{
    tree[n].l=l;
    tree[n].r=r;
    if(l==r)
    {
        tree[n].m=a[l];return;
    }
    else
    {
        build(n*2,l,(l+r)/2);
        build(n*2+1,(l+r)/2+1,r);
        tree[n].m=tree[n*2].m>tree[n*2+1].m?tree[n*2].m:tree[n*2+1].m;
    }
}
void find(int n,int a,int b)
{
    if(a<=tree[n].l&&b>=tree[n].r) ans=tree[n].m>ans?tree[n].m:ans;//注意a,b,r,l的关系!!!
    else if(a>tree[n].r||b<tree[n].l) return;
    else 
    {
        find(n*2,a,b);
        find(n*2+1,a,b);
    }
}
int main()
{
    int n,m,i,j,r,l;
    scanf("%d",&n);
    for(i=1;i<=n;i++) scanf("%d",&a[i]);
    build(1,1,n);
    scanf("%d",&m);
    while(m--)
    {
        scanf("%d%d",&l,&r);
        ans=-1;
        l++;r++;
        find(1,l,r);
        printf("%d\n",ans);
    }
}

哼叽~

51Nod—1174 区间中最大的数 线段树模版

标签:--   最大   int   blog   线段树   space   pre   帮助   pac   

原文地址:http://www.cnblogs.com/wsblm/p/7155135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!