题目:
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 aiand bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation.
Output
Print a single integer — the number of inversions in the resulting sequence.
Examples
Input
2
4 2
1 4
Output
4
Input
3
1 6
3 4
2 5
Output
15
Note
In the first sample the sequence is being modified as follows: . It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).
一个无限数列,1,2,3,4,...,n....,给n个数对<i,j>把数列的i,j两个元素做交换。求交换后数列的逆序对数。
很容易想到离散化+树状数组。因为数据过大,无法将所涉及到的树一 一存入数组。
看了网上题解后才知道,可以把没有用到的数字段化成点。然后用树状数组算一下就好了。
然后我用一个数组记录每个点的长度。比如 <1,2><5,6>,1,2,3,4,5,6只有1,2,5,6用到了,那么离散化为1,2,3,4,5,f[1]=f[2]=f[4]=f[5]=1,f[3]=2,数对变为<1,2><4,5>
AC代码:
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
typedef long long ll;
const int INF=6e5+5;//注意数组开大一点
struct node
{
int val;
int pos;
} x[INF];
int a[INF];
int b[INF];
int c[INF];
int d[INF];
int f[INF];
bool cmp(node p1,node p2)
{
return p1.val <p2.val ;
}
int lowbit(int x)
{
return x & (-x);
}
int sum(int n)
{
int ans = 0;
while (n > 0)
{
ans += c[n];
n -= lowbit(n);
}
return ans;
}
void update(int pos, int n, int num)
{
while(pos <= n)
{
c[pos] += num;
pos += lowbit(pos);
}
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < 2 * n; ++i)
{
scanf("%d", &x[i].val);
x[i].pos = i;//序号和值一一对应
}
// 离散化
sort(x, x + 2 * n,cmp);
int cnt = 0;
for (int i = 0; i < 2 * n; ++i)
{
if (i == 0 || x[i].val > x[i - 1].val)//实现了去重
{
++cnt;
if (x[i].val - x[i - 1].val > 1)
{
f[cnt++] = x[i].val - x[i - 1].val - 1;
}
f[cnt] = 1;
}
if (x[i].pos & 1)//结构体已排好序,用他的相对位置代替其本身大小。
b[x[i].pos / 2] = cnt;//0和1除以2后是0 相同,同理2和3除以2后是1相同。
else
a[x[i].pos / 2] = cnt;
}
for (int i = 1; i <= cnt; ++i) d[i] = i;
//交换
for (int i = 0; i < n; ++i)
{
swap(d[a[i]], d[b[i]]);
}
ll ans = 0;
ll tot = 0;
for (int i = 1; i <= cnt; ++i)
{
ll temp = sum(d[i]);
ans += (tot - temp) * f[i];
update(d[i], cnt, f[i]);
tot += f[i];
}
printf("%lld", ans);
return 0;
}