Blue Bridge Daily Zhenti children line up

topic source

2014 Blue Bridge Cup Provincial

Topic link:
https://www.lanqiao.cn/problems/222/learning//

test center

Merge, Inverse Pairs, Tree Arrays

Video explanation

https://www.bilibili.com/video/BV1VY411J7nP

ideas

This topic can be clearly related to bubble sort, we need to know that for the first iiHow many students are to the left of i students (L i L_iLi) is taller than him, how many classmates are on the right ( R i R_iRi) is lower than his, then we find that for iiThe actual number of exchanges that i students will make is( L i + R i ) (L_i + R_i)(Li+Ri) , and since the former is actually the inverse pair, and the latter is the order pair, then we are going to find the number of inverse pairs through thetree array, and then find the order pair in reverse. The arithmetic sequence at the beginning can be calculated by its summation formula. Please see the code for details. Of course, the writing method of merge sort is left to everyone's thinking.

code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f

const int N = 1e6 + 10;
ll a[N],ans[N],n;

struct BIT{
    
    
	ll tree[N<<2];
	ll lowbit(ll x) {
    
    return -x & x;}
	
	void update(ll x,ll k) {
    
    
		while(x < N) {
    
    
			tree[x] += k;
			x += lowbit(x);
		}
	}
	ll query(ll x) {
    
    
		ll ans = 0LL;
		while(x){
    
    
			ans += tree[x];
			x -= lowbit(x);
		}
		return ans;
	}
	void clear(){
    
    
		memset(tree,0,sizeof tree);
	}
}bit;



int main()
{
    
    
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n;
	for(int i = 1;i <= n; ++i) cin>>a[i],a[i]++;
	
	for(ll i = 1;i <= n; ++i) {
    
    
		bit.update(a[i],1LL);
		ans[i] = i - bit.query(a[i]);
	}
	bit.clear();
	for(ll i = n;i >= 1; --i) {
    
    
		bit.update(a[i],1LL);
		ans[i] += bit.query(a[i] - 1LL);
	}
	ll res = 0LL;
	for(int i = 1;i <= n; ++i)  
		res += (ans[i] + 1LL) * ans[i] / 2LL;
	cout<<res<<endl;
	
	
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_46201544/article/details/123858201