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 ≤ 109, ai ≠ bi) — the arguments of the swap operation.
Output
Print a single integer — the number of inversions in the resulting sequence.
Example
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).
题意:给你n种位置置换的操作,求最后的逆序数,位置达到了 1e9
考虑缩点的操作
离散化,但是对于1e5的询问,对结果有影响的不止是询问的l,r 别的区间也会有影响,但可以发现影响的权值就是区间大小,所以考虑加点,把其余的区间缩成一个点,值是它的区间长度,最后求一遍逆序对就好
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
typedef long long ll;
int b[2*N+10];
int num[2*N+10];
ll c[4*N+10];
int has[4*N+10];
int shu[4*N+10];
#define lowbit(x) x&(-x)
int top;
struct node
{
int l,r;
}s[N+10];
ll sum(int x)
{
ll ans=0;
while(x>0)
{
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
void update(int x,int val)
{
while(x<=top){
c[x]+=1ll*val;
x+=lowbit(x);
}
}
int main()
{
int n;
scanf("%d",&n);
int tot=1;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&s[i].l,&s[i].r);
b[tot++]=s[i].l;
b[tot++]=s[i].r;
}
sort(b+1,b+tot);
int cnt=unique(b+1,b+tot)-b-1;
top=0;
for(int i=1;i<=cnt;i++)
{
if(i>1&&b[i]-b[i-1]>1)
{
has[++top]=b[i-1]+1;
num[top]=b[i]-b[i-1]-1;
}
has[++top]=b[i];
num[top]=1;
}
for(int i=1;i<=top;i++)
shu[i]=i;
for(int i=1;i<=n;i++)
{
int x=lower_bound(has+1,has+top+1,s[i].l)-has;
int y=lower_bound(has+1,has+top+1,s[i].r)-has;
swap(shu[x],shu[y]);
}
ll ans=0;
for(int i=1;i<=top;i++)
{
ans+=(sum(top)-sum(shu[i]))*num[shu[i]];
update(shu[i],num[shu[i]]);
}
printf("%lld\n",ans );
}