hdu 1166敵兵布陣(線段樹或者樹狀數組)

來源:互聯網
上載者:User

http://acm.hdu.edu.cn/showproblem.php?pid=1166

不懂得可以看劉汝佳訓練指南P194

//線段樹版:#include <iostream>#include <cstdio> #include <cstring>using namespace std;int n,s[50005*4];void update(int id,int d,int L,int R,int O){int M=L+(R-L)/2;if(L==R) s[O]+=d;else{if(id<=M) update(id,d,L,M,O*2); else update(id,d,M+1,R,O*2+1);s[O]=s[O*2]+s[O*2+1];}}int query(int ql,int qr,int L,int R,int O){int M=L+(R-L)/2,ans=0;if(ql<=L&&R<=qr) return s[O];if(ql<=M) ans+=query(ql,qr,L,M,O*2);if(M<qr)  ans+=query(ql,qr,M+1,R,O*2+1);return ans;}int main(int argc, char *argv[]){    int t,i,d,k=1; char a[10];    scanf("%d",&t);    while(t--!=0)    {        printf("Case %d:\n",k++);            scanf("%d",&n);            memset(s,0,sizeof(s));            for(i=1;i<=n;i++)            {                scanf("%d",&d); update(i,d,1,n,1);            }                while(scanf("%s",a))            {                if(a[0]=='E') break;                scanf("%d%d",&i,&d);                if(a[0]=='Q') printf("%d\n",query(i,d,1,n,1));                else if(a[0]=='A') update(i,d,1,n,1);                else if(a[0]=='S') update(i,-d,1,n,1);            }        }    return 0;}


//樹狀數組版:#include <iostream>#include <cstdio> #include <cstring>using namespace std;int n,s[50005];int LowBit(int x){    return x&-x;  }void Add(int x,int d){    while(x<=n)    {  s[x]+=d;  x+=LowBit(x);}}int Sum(int x){    int ans=0;    while(x>0)    {    ans+=s[x];  x-=LowBit(x); }    return ans;}int main(int argc, char *argv[]){    int t,i,d,k=1; char a[10];    scanf("%d",&t);    while(t--!=0)    {        printf("Case %d:\n",k++);            scanf("%d",&n);            memset(s,0,sizeof(s));            for(i=1;i<=n;i++)            {                scanf("%d",&d); Add(i,d);            }                while(scanf("%s",a))            {                if(a[0]=='E') break;                scanf("%d%d",&i,&d);                if(a[0]=='Q') printf("%d\n",Sum(d)-Sum(i-1));                else if(a[0]=='A') Add(i,d);                else if(a[0]=='S') Add(i,-d);            }        }    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.