Fenwick tree
The main use: Fenwick tree is mainly used to refer to a little modify or query the range of topics, mainly
Time complexity can be reduced.
Fenwick tree is actually a binary storage methods involved.
To store data by Fenwick tree can make the process more convenient query and modify in.
The number of array-like query:
int getsum(int x) { int ans=0; for(int i=x;i>0;i-=lowbit(i)) ans+=tree[i]; return ans; }
Fenwick tree changes:
void add(int x,int y) { for(int i=x;i<=n;i+=lowbit(i)) tree[i]+=y; }
lowbit function:
int lowbit(int t) { return t&(-t); }
The above code can achieve single query and modify the interval
-------------------------- separator ---------------------- ------------------------------------------------
POJ2299:
We can learn by reading the title of this topic is seeking to reverse the array, as the following theorem: a random number sequence = reverse sequence under conditions allowing only two adjacent elements of the exchange, the number of exchanges to obtain an ordered sequence
So how to find it in reverse? It can be achieved by Fenwick tree.
Algorithms general process:
1. First of discrete feed array so that each data feed from relatively
2. The use of standard operating Fenwick tree to come to reverse right.
So why discrete data, it is because we are in the process of storing, if there is a large number, you need a bit more space for storage, so the need for initial data into discrete nature.
First insert the number of array-like array, and then modify it:
#include<iostream> #include<algorithm> typedef long long ll; #include<cstring> using namespace std; #define maxn 510000 int c[maxn],n,a[maxn]; struct node { int val,pos; }p[maxn]; bool cmp(node a,node b) { return a.val<b.val; } void add(int i){ while(i<=n){ c[i]+=1; i+=i&-i; } } int sum(int i) { int s=0; while(i) { s+=c[i]; i-=i&(-i); } return s; } int main() { while(cin>>n) { if(n==0) break; for(int i=1;i<=n;i++) { int v; cin>>v; p[i].val=v; p[i].pos=i; } memset(c,0,sizeof(c)); sort(p+1,p+1+n,cmp); for(int i=1;i<=n;i++) a[p[i].pos]=i; ll ans=0; for(int i=1;i<=n;i++) { add(a[i]); ans+=i-sum(a[i]); } cout<<ans<<endl; } return 0; }
If you do not know can see this blog: https://blog.csdn.net/guhaiteng/article/details/52138756
Featured Training Address : https: //vjudge.net/contest/295361