列表

详情


NC17410. inv

描述

Kanade has an even number n and a permutation b of all of the even numbers in [1,n]
Let a denote an array [1,3,5....n-1] , now you need to find a permutation of [1,n] satisfy both a and b are subsequence of it and minimize the number of inverse pair of it.

输入描述

The first line has a positive even integer n

The second line has n/2 positive even integers b[i]

输出描述

Output the number of inverse pair of the permutation you find.

示例1

输入:

6
2 6 4

输出:

2

说明:

[1,2,3,5,6,4]

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 43ms, 内存消耗: 2532K, 提交时间: 2018-08-13 22:20:48

#include <cstdio>
#include <queue>

typedef long long LL;
const int N = 200005;

int n, a[N], tr[N];
LL ans;
std::priority_queue<int> Q;

void Add(int x) {
  for (; x <= n; x += x & -x) ++tr[x];
}
int Query(int x, int re = 0) {
  for (; x; x -= x & -x) re += tr[x];
  return re;
}

int main() {
  scanf("%d", &n);
  n /= 2;
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &a[i]);
    a[i] /= 2;
    ans += Query(n) - Query(a[i]);
    Add(a[i]);
    Q.push(a[i]);
    if (a[i] < Q.top()) {
      ans += Q.top() - a[i];
      Q.pop();
      Q.push(a[i]);
    }
  }
  printf("%lld\n", ans);
  
  return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 42ms, 内存消耗: 2012K, 提交时间: 2018-08-02 21:04:48

#include<bits/stdc++.h>
using namespace std;
#define N 100010
#define LL long long
int n,a[N],tree[N];
LL ans=0;
priority_queue<int>q;
void add(int x){
	for(;x<=n;x+=x&-x)tree[x]++;
}
int sum(int x){
	int ret=0;
	for(;x;x-=x&-x)ret+=tree[x];
	return ret; 
} 
int main(){
	scanf("%d",&n);n/=2;
	for(int i=1;i<=n;i++)scanf("%d",&a[i]),a[i]/=2;
	for(int i=1;i<=n;i++)
		add(a[i]),ans+=i-sum(a[i]);
	for(int i=1;i<=n;i++){
		q.push(a[i]);
		if(q.top()>a[i])
			ans+=q.top()-a[i],q.pop(),q.push(a[i]);
	}cout<<ans<<endl;
	return 0;
}

上一题