Balanced Lineup(線段樹—指標實現),balancedlineup

來源:互聯網
上載者:User

Balanced Lineup(線段樹—指標實現),balancedlineup

線段樹這一類樹狀結構一般可以用兩種形式來實現—數組和指標。 下面學習了一下別人的指標實現的線段樹。

和數組實現的一樣分為三步:建樹,添加值,查詢。

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;const int INF_MAX = -999999999;const int INF_MIN = 999999999;int n,q,a,b,t=1,MAX=INF_MAX,MIN=INF_MIN;struct node{    int l,r;    int MAX,MIN;    node *left, *right;};node tree[1000000];//可以事先建立結點數組,也可以在建樹的過程中動態建立結點,但是這樣可以節省遞迴清記憶體的時間void built(node *root,int l,int r){    root->l = l;    root->r = r;    root->MAX = INF_MAX;    root->MIN = INF_MIN;              //將結點維護的最值初始化。    if(l!=r){        root->left = &tree[t++];        root->right = &tree[t++];        built(root->left,l,(root->l+root->r)/2);        built(root->right,(root->l+root->r)/2+1,r);    }}void update(node *root,int i,int v){    if(root->l == i&&root->r == i) {        root->MAX = root->MIN = v; return ;    //找到該結點就賦值    }    root->MIN = min(root->MIN,v);        //遞迴改變母節點的值    root->MAX = max(root->MAX,v);    if(i<=(root->l+root->r)/2) update(root->left,i,v);    else update(root->right,i,v);}void query(node *root,int l,int r){    if(root->MAX<=MAX&&root->MIN>=MIN) return ;       if(l==root->l&&r==root->r) {        MIN = min(root->MIN,MIN);        MAX = max(root->MAX,MAX);        return ;    }    if(r<=(root->l+root->r)/2) query(root->left,l,r);    else if(l>=(root->l+root->r)/2+1) query(root->right,l,r);    else {        query(root->left,l,(root->l+root->r)/2);        query(root->right,(root->l+root->r)/2+1,r);    }}int main(){    scanf("%d%d",&n,&q);    built(tree,1,n);    for(int i=1;i<=n;i++){        scanf("%d",&a);        update(tree,i,a);    }    while(q--){        scanf("%d%d",&a,&b);        MAX = INF_MAX;        MIN = INF_MIN;        query(tree,a,b);        printf("%d\n",MAX-MIN);    }    return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.