算法筆記--樹狀數組
阿新 • • 發佈:2017-10-29
font sdn ref 數組 lowbit fine while sizeof with
區間和模板:
const int N=1e5+5; int c[N]; int n; int lowbit(int x) { return x&(-x); } int sum(int x) { int ret=0; while(x) { ret+=c[x]; x-=lowbit(x); } return ret; } void update(int x,int d) { while(x<=n) { c[x]+=d; x+=lowbit(x); } }
1.單點更新,區間求和
HDU - 1166
#include<bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define mem(a,b) memset(a,b,sizeof(a)) const int N=1e5+5; int c[N]; int n; int lowbit(int x) { return x&(-x); } int sum(int x) {View Codeint ret=0; while(x) { ret+=c[x]; x-=lowbit(x); } return ret; } void update(int x,int d) { while(x<=n) { c[x]+=d; x+=lowbit(x); } } int main() { ios::sync_with_stdio(false); cin.tie(0); int T,a,l,r; int cnt=0; string s; cin>>T; while(T--) { cin>>n; mem(c,0); for(int i=1;i<=n;i++)cin>>a,update(i,a); cout<<"Case "<<++cnt<<":"<<endl; while(cin>>s) { if(s=="End")break; if(s=="Query") { cin>>l>>r; cout<<sum(r)-sum(l-1)<<endl; } else if(s=="Add") { cin>>l>>r; update(l,r); } else if(s=="Sub") { cin>>l>>r; update(l,-r); } } } return 0; }
2.區間更新,單點求值
HDU - 1556
#include<bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define mem(a,b) memset(a,b,sizeof(a)) const int N=1e5+5; int c[N]; int n; int lowbit(int x) { return x&(-x); } int sum(int x) { int ret=0; while(x) { ret+=c[x]; x-=lowbit(x); } return ret; } void update(int x,int d) { while(x<=n) { c[x]+=d; x+=lowbit(x); } } int main() { ios::sync_with_stdio(false); cin.tie(0); int l,r; while(cin>>n) { mem(c,0); for(int i=1;i<=n;i++) { cin>>l>>r; update(l,1); update(r+1,-1); } for(int i=1;i<=n;i++) { cout<<sum(i); if(i!=n)cout<<‘ ‘; else cout<<endl; } } return 0; }View Code
參考博客:http://blog.csdn.net/yexiaohhjk/article/details/51077545
算法筆記--樹狀數組