topic:
The data range is large, and the adjacent trees are exchanged to make the order
Problem-solving instructions: The key is to know that the number of times each number is swapped is the number of trees in front of it that are larger than it. Maintain it with a tree array~
AC code:
#include<iostream> #include<algorithm> #include<string.h> #include<map> using namespace std; typedef long long ll; const int MAXN=500010; map<int,int>mp; int be[MAXN]; int temp[MAXN]; int c[MAXN]; int get(int x){ int res=0; for(;x<=MAXN;x+=(x&-x))res+=c[x]; return res; } void modify(int x,int sum){ for(;x;x-=(x&-x))c[x]+=sum; } int main(){ int n; ios::sync_with_stdio(false); cin>>n; for(int i=0;i<n;i++){ cin>>be[i]; temp[i]=be[i]; } sort(temp,temp+n); int m=unique(temp,temp+n)-temp; for(int i=0;i<m;i++){ mp[temp[i]]=i+1; } memset(c,0,sizeof(c)); ll ans=0; for(int i=0;i<n;i++){ ans+=(ll)get(mp[be[i]]); modify(mp[be[i]],1); } cout<<ans<<endl; }