Recently learned a tree-like array, this problem tangled for a long time, after all, because there is no understanding of the tree array how to use.
I feel that many of the great gods on the internet are only talking about the principle, for our novice beginners are afraid to be scared away.
Here I would like to use the pragmatic approach (in fact, I think its principle should be more enlightening to us, may bring a lot of potential benefits):
It is important to note that the bit array in the bit's implementation code must initially be zeroed, and this array is not used to store elements, but to implement this data structure. The element you need to store is added by the Add function, and the sum is implemented by the SUM function, and the structure of this bit array is not easy to understand for a novice, and we don't have to worry about that.
Also pay attention to a place, in the Add function that n, to open large enough, or you are not added, for example, if you put n=10, sum (100) will get 0.
For example: Enter n elements to find the first n elements. The code is as follows
#include <cstdio> #include <cstring> #include <iostream>using namespace std;int bit[1000],n;int sum ( int i) { int s = 0; while (i>0) { s+=bit[i]; i-=i&-I.; } return s;} int add (int i,int x) { while (i <= N) { Bit[i] + = x; i + = (I & i); }} int main () { while (~scanf ("%d", &n)) { memset (bit,0,sizeof (bit)); for (int i=1;i<=n;i++) { int x; scanf ("%d", &x); Add (i,x); } for (int i=1;i<=n;i++) printf ("%d\n", sum (i)); } return 0;}
Believe that the above code can be clearly understood, the first element is to enter into the Add function, you input the i is a few, then this element is the tree array of the first element. Regardless of the bit array, this array is just an auxiliary function that exists to implement a particular data structure.
The problem code is reference to someone else's.
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include < queue> #include <vector> #include <map>using namespace std;typedef long long ll;const int max_n = 20000+4;ll Cnt_bit[20005]={0},distance_bit[20005]={0};int n;struct Point {int v,x;} A[20005];bool CMP (point A,point B) {return A.V<B.V;} ll Sum_ (ll *bit,int i) {ll s = 0; while (i>0) {s+=bit[i]; I-=i &-I.; } return s;} ll sum (ll *a,int I,int j) {return sum_ (a,j-1)-sum_ (a,i-1);} void Add (ll *bit,int I,int x) {while (i<=max_n) {Bit[i] + = x; i + = i&-i; }}int Main () {ll tot = 0; scanf ("%d", &n); memset (cnt_bit,0,sizeof (cnt_bit)); memset (distance_bit,0,sizeof (distance_bit)); for (int i=0;i<n;i++) scanf ("%d%d", &a[i].v,&a[i].x); Sort (a,a+n,cmp); for (int i=0;i<n;i++) {int v = A[I].V; int x = a[i].x; ll left = SUM (cnt_bit,1,x); ll right = SUM (cnt_bit,x+1,max_n); tot+= ((Left*x-sum (distance_bit,1,x)) + (sum (distance_bit,x+1,max_n)-right*x)) *v; Add (cnt_bit,a[i].x,1); Add (distance_bit,a[i].x,a[i].x); } printf ("%lld\n", tot); return 0;}
Moofest (POJ-1990) (tree-like array)