分塊法 hdu1166 敵兵布陣

來源:互聯網
上載者:User

當然啦,這題最正規的方法當然是最標準的單點更新的線段樹咯


最近發現了分塊法這一神器,正嘗試水各種資料結構中(線段樹,伸展樹,主席樹....),幾乎是萬能的(效率只慢了一點)

優勢在於

1.佔用的空間非常低.

2.非常容易寫

3.對於比較複雜的維護和各種資料結構的鑲套,能較好的處理


缺點當然就是沒有標準的那種資料結構塊(一般的資料結構複雜度是O(nlogn),這個的複雜度是O(msqrt(n)),有時候還是會卡時間的)


#include<cstdio>#include<cmath>#include<cstring>#include<algorithm>using namespace std;const int MX=50000+5;int n,unit;int A[MX],S[MX];void build(){    unit=sqrt(n+0.5);    memset(S,0,sizeof(S));    for(int i=1;i<=n;i++){        scanf("%d",&A[i]);        int u=sqrt(i+0.5);        S[u]+=A[i];    }}void update(int x,int d){    int u=sqrt(x+0.5);    S[u]+=d;A[x]+=d;}int get_sum(int u,int L,int R){    int l=max(u*u,L),r=min((u+1)*(u+1)-1,R),ret=0;    for(int i=l;i<=r;i++){        ret+=A[i];    }    return ret;}int query(int L,int R){    int uL=sqrt(L+0.5),uR=sqrt(R+0.5),ret=0;    for(int i=uL+1;i<=uR-1;i++){        ret+=S[i];    }    ret+=get_sum(uL,L,R);    if(uL!=uR) ret+=get_sum(uR,L,R);    return ret;}int main(){    char op[10];    int T,ansk=0;    scanf("%d",&T);    while(T--){        printf("Case %d:\n",++ansk);        scanf("%d",&n);        build();        while(scanf("%s",op),op[0]!='E'){            int a,b;            scanf("%d%d",&a,&b);            if(op[0]=='A'){                update(a,b);            }else if(op[0]=='S'){                update(a,-b);            }else{                printf("%d\n",query(a,b));            }        }    }    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.