-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathfenwick_BIT_tree.cpp
More file actions
62 lines (62 loc) · 1.15 KB
/
fenwick_BIT_tree.cpp
File metadata and controls
62 lines (62 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* Use of BIT
* Question:https://www.hackerearth.com/challenge/college/codezilla-prelims/algorithm/childhood/
*/
#include<bits/stdc++.h>
using namespace std;
typedef long l;
void update_BIT(int pos,int BIT[],int msz,int val=1)
{
while(pos<=msz)
{
BIT[pos]+=val;
pos+=pos&(-pos);
}
}
int getSum(int pos,int BIT[])
{
int sum=0;
while(pos!=0)
{
sum+=BIT[pos];
pos-=pos&(-pos);
}
return sum;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int g[n];
int f[n];
map<int,int> mp;
for(int i=0;i<n;++i)
{
cin>>g[i];
}
for(int i=0;i<n;++i)
{
cin>>f[i];
}
for(int i=0;i<n;++i)
{
mp[f[i]]=g[i];
}
l ans=0;
int BIT[100005]={0};
for(auto i=mp.rbegin();i!=mp.rend();++i)
{
int c=i->second;
ans+=abs(i->first-c+getSum(i->second-1,BIT));
update_BIT(i->second,BIT,n);
}
cout<<2*ans<<endl;
}
return 0;
}