codeforces 540 E. Infinite Inversions (离散化 + 树状数组)

E. Infinite Inversions
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj.

Input

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence.

Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109ai ≠ bi) — the arguments of the swap operation.

Output

Print a single integer — the number of inversions in the resulting sequence.

Sample test(s)
input
2
4 2
1 4
output
4
input
3
1 6
3 4
2 5
output
15

把交换点和交换点之间的区间都当作点,进行离散化,数据量最多达到400000,然后就可以用树状数组处理了

#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

#define P pair<int ,int>
#define PB push_back
#define X first
#define Y second
#define LL __int64

const int N = 1e5 + 5;

vector<P> pool;
int pool_cnt;

int u[N], v[N];

int id[N * 4];
int num[N * 4];

int BIT[N * 4];
int lowbit(int x) { return x & -x; }
int sum(int x) {
	int s = 0;
	while (x > 0) {
		s += BIT[x];
		x -= lowbit(x);
	}
	return s;
}
void update(int x, int c) {
	while (x <= pool_cnt) {
		BIT[x] += c;
		x += lowbit(x);
	}
}

int get_p(int x) {
	return lower_bound(pool.begin(), pool.begin() + pool_cnt, P(x, 0)) - pool.begin() + 1;
}

int main() {
	int n;
	cin>>n;
	for(int i = 0; i < n; ++i) {
		cin>>u[i]>>v[i];
		pool.PB(P(u[i], 1));
		pool.PB(P(v[i], 1));
	}
	sort(pool.begin(), pool.end());
	pool_cnt = unique(pool.begin(), pool.end()) - pool.begin();
	for(int i = 0; i < pool_cnt - 1; ++i) {
		int x = pool[i].X + 1;
		if(x == pool[i + 1].X) continue;
		int y = pool[i + 1].X - x;
		pool.PB(P(x, y));
	}
	sort(pool.begin(), pool.end());
	pool_cnt = unique(pool.begin(), pool.end()) - pool.begin();
	for(int i = 0; i < pool_cnt; ++i) {
		id[i + 1] = i + 1;
		num[i + 1] = pool[i].Y;
	}
	for(int i = 0; i < n; ++i) {
		u[i] = get_p(u[i]);
		v[i] = get_p(v[i]);
		swap(id[u[i]], id[v[i]]);
	}
	LL ans = 0;
	for(int i = pool_cnt; i > 0; --i) {
		LL tmp = sum(id[i]);
		ans += tmp * num[id[i]];
		update(id[i], num[id[i]]);
	}
	cout<<ans<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值