士兵杀敌(二)(线段树+树状数组)
生活随笔
收集整理的這篇文章主要介紹了
士兵杀敌(二)(线段树+树状数组)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
士兵殺敵(二)
時間限制:1000 ms? |?????????? 內存限制:65535 KB 難度:5 描述南將軍手下有N個士兵,分別編號1到N,這些士兵的殺敵數都是已知的。
小工是南將軍手下的軍師,南將軍經常想知道第m號到第n號士兵的總殺敵數,請你幫助小工來回答南將軍吧。
南將軍的某次詢問之后士兵i可能又殺敵q人,之后南將軍再詢問的時候,需要考慮到新增的殺敵數。
線段樹: 1 #include<stdio.h> 2 #include<string.h> 3 #include<math.h> 4 #include<algorithm> 5 using namespace std; 6 #define MAX(x,y)(x>y?x:y) 7 #define MIN(x,y)(x<y?x:y) 8 #define lson root<<1,l,mid 9 #define rson root<<1|1,mid+1,r 10 #define NOW tree[root].val=tree[root<<1].val+tree[root<<1|1].val; 11 #define L tree[root].l 12 #define R tree[root].r 13 #define V tree[root].val 14 //#define LOCAL 15 const int INF=0x3f3f3f3f; 16 const int MAXN=1000010; 17 struct Node{ 18 int l,r,val; 19 }; 20 int X,Y,ans; 21 Node tree[MAXN<<2]; 22 void build(int root,int l,int r){ 23 L=l;R=r; 24 if(l==r)scanf("%d",&V); 25 else{ 26 int mid=(l+r)>>1; 27 build(lson); 28 build(rson); 29 NOW; 30 } 31 } 32 void update(int root){ 33 if(L==X&&R==X)V+=Y; 34 else{ 35 int mid=(L+R)>>1; 36 if(mid>=X)update(root<<1); 37 else update(root<<1|1); 38 NOW; 39 } 40 } 41 void query(int root){ 42 if(L>=X&&R<=Y)ans+=V; 43 else{ 44 int mid=(L+R)>>1; 45 if(mid>=X)query(root<<1); 46 if(mid<Y)query(root<<1|1); 47 } 48 } 49 void input(){ 50 char s[10]; 51 int N,M; 52 scanf("%d%d",&N,&M); 53 build(1,1,N); 54 while(M--){ 55 scanf("%s%d%d",s,&X,&Y); 56 if(!strcmp(s,"ADD"))update(1); 57 else{ 58 ans=0; 59 query(1); 60 printf("%d\n",ans); 61 } 62 } 63 } 64 int main(){ 65 #ifdef LOCAL 66 freopen(data.in,"r",stdin); 67 freopen(data.out,"w",stdout); 68 #endif 69 input(); 70 return 0; 71 }
樹狀數組:
1 #include<stdio.h> 2 #include<string.h> 3 #include<math.h> 4 #include<algorithm> 5 using namespace std; 6 #define MAX(x,y)(x>y?x:y) 7 #define MIN(x,y)(x<y?x:y) 8 //#define LOCAL 9 const int INF=0x3f3f3f3f; 10 const int MAXN=1000010; 11 int tree[MAXN]; 12 int N; 13 int lowbit(int x){ 14 return x&(-x); 15 } 16 void update(int x,int y){ 17 while(x<=N){ 18 tree[x]+=y; 19 x+=lowbit(x); 20 } 21 } 22 int query(int x){ 23 int ans=0; 24 while(x){ 25 ans+=tree[x]; 26 x-=lowbit(x); 27 } 28 return ans; 29 } 30 int main(){ 31 #ifdef LOCAL 32 freopen(data.in,"r",stdin); 33 freopen(data.out,"w",stdout); 34 #endif 35 int M; 36 scanf("%d%d",&N,&M); 37 int a,b; 38 for(int i=1;i<=N;i++){ 39 scanf("%d",&a); 40 update(i,a); 41 } 42 char s[10]; 43 while(M--){ 44 scanf("%s",s); 45 scanf("%d%d",&a,&b); 46 if(!strcmp(s,"ADD"))update(a,b); 47 else 48 printf("%d\n",query(b)-query(a-1)); 49 } 50 return 0; 51 }?
轉載于:https://www.cnblogs.com/handsomecui/p/4893092.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的士兵杀敌(二)(线段树+树状数组)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HBase 性能优化笔记
- 下一篇: hibernateTemplate的lo