POJ 2823 Sliding Window 線段樹區間求和問題

來源:互聯網
上載者:User

標籤:roo   c++   name   href   nbsp   ;;   define   div   uil   

題目連結

線段樹區間求和問題,維護一個最大值一個最小值即可,線段樹要用C++交才能過。

注意這道題不是求三個數的最大值最小值,是求k個的。

還有一種做法是單調隊列,耗時更少。

 

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>#define N 1000005using namespace std;int n,k;struct Tree{    int l,r,mx,mn;}tree[N*4];void build(int root,int l,int r){    tree[root].l=l;    tree[root].r=r;    if(l==r)    {        scanf("%d",&tree[root].mx);        tree[root].mn=tree[root].mx;        return;    }    int mid=(l+r)>>1;    build(root<<1,l,mid);    build(root<<1|1,mid+1,r);    tree[root].mx=max(tree[root<<1].mx,tree[root<<1|1].mx);    tree[root].mn=min(tree[root<<1].mn,tree[root<<1|1].mn);}int querymx(int root,int l,int r){    if(l<=tree[root].l&&r>=tree[root].r) return tree[root].mx;    int mid=(tree[root].l+tree[root].r)>>1,ret=-1000000000;    if(l<=mid) ret=max(querymx(root<<1,l,r),ret);    if(r>mid) ret=max(querymx(root<<1|1,l,r),ret);    return ret;}int querymn(int root,int l,int r){    if(l<=tree[root].l&&r>=tree[root].r) return tree[root].mn;    int mid=(tree[root].l+tree[root].r)>>1,ret=1000000000;    if(l<=mid) ret=min(querymn(root<<1,l,r),ret);    if(r>mid) ret=min(querymn(root<<1|1,l,r),ret);    return ret;}void pr(){    for(int i=1;i<=n-k+1;i++)    printf("%d ",querymn(1,i,i+k-1));    puts("");    for(int i=1;i<=n-k+1;i++)    printf("%d ",querymx(1,i,i+k-1));    puts("");}int main(){    while(scanf("%d%d",&n,&k)!=EOF)    {        build(1,1,n);        pr();    }    return 0;}

 

POJ 2823 Sliding Window 線段樹區間求和問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.