1. 程式人生 > 其它 >位運算中x&(-x) Lowbit(x)的理解

位運算中x&(-x) Lowbit(x)的理解

技術標籤:筆記資料結構演算法

跟大佬學習樹狀陣列的學習筆記:
在這裡插入圖片描述
取到的結果就是把自身x最低位1和後面的0儲存,前面都不要了
e.g:
lowbit(6):6的二進位制是(110)所以結果就是(10)
lowbit(7):7的二進位制是(111)所以結果就是(1)
然後把結果轉化10進位制就可以了
快速辦法直接看 最低位1取到的是第幾位,然後2的幾次方就可以了
比如lowbit(6) 最低位1 在第1位上 所以2^1=2;
lowbit (7) 最低位1 在第0位上 所以2^0=1
在這裡插入圖片描述
附上一個特別棒的網站,幫助理解(動畫演示程式碼):
https://visualgo.net/zh/fenwicktree

附上樹狀陣列程式碼(方便以後自己學習):

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <string>
#include <vector>
#define For(a,b) for(int a=0;a<b;a++)
#define mem(a,b) memset(a,b,sizeof(a))
#define _mem(a,b) memset(a,0,(b+1)<<2) #define lowbit(a) ((a)&-(a)) using namespace std; typedef long long ll; const int maxn = 5*1e4+5; const int INF = 0x3f3f3f3f; int c[maxn]; void update(int x,int y,int n){ for(int i=x;i<=n;i+=lowbit(i)) c[i] += y; } int getsum(int x){ int
ans = 0; for(int i=x;i;i-=lowbit(i)) ans += c[i]; return ans; } int main() { int t; int n; int x,y,z; string s; cin >> t ; for(int j=1;j<=t;j++){ scanf("%d",&n); _mem(c,n); //初始化陣列中前n+1個數為0 for(int i=1;i<=n;i++){ scanf("%d",&z); update(i,z,n); } cout <<"Case "<<j<<":"<<endl; while(1){ cin >> s; if(s[0] == 'E') break; scanf("%d%d",&x,&y); if(s[0] == 'Q') cout << getsum(y)-getsum(x-1)<<endl; else if(s[0] == 'A') update(x,y,n); else update(x,-y,n); } } return 0; }