CodeForces - 540E Infinite Inversions 树状数组+离散化

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.

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).

题解:离散化点和区间 给定对应的权值即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
#define M(a, b) memset(a, b, sizeof(a))
#define lowbit(x) (x&(-x))
typedef long long ll;
const int N=4*1e5+10;
ll sum[N];
int n,m,b[N],id[N],num[N],cnt,pos[N];
struct node{
    int l,r;
}a[N];
void add(int x,int aa)
{
    while(x)
    {
        sum[x]+=aa;
        x-=lowbit(x);
    }
}
int query(int x)
{
    int ans=0;
    while(x<=cnt)
    {
        ans+=sum[x];
        x+=lowbit(x);
    }
    return ans;
}
int main()
{
    int l,r;
	while(~scanf("%d",&n))
    {
        cnt=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d%d",&l,&r);
            a[i].l=l,a[i].r=r;
            b[i*2-1]=l,b[i*2]=r;
        }
        sort(b+1,b+1+n*2);
        sum[0]=0;
        for(int i=1;i<=2*n;i++)
        {
            sum[i]=0;
            if(b[i]==b[i+1]) continue;
            id[++cnt]=b[i];
            num[cnt]=1;
            if(b[i]+1==b[i+1]||i==2*n) continue;
            id[++cnt]=b[i]+1;
            num[cnt]=b[i+1]-b[i]-1;
        }
        for(int i=0;i<=cnt;i++)pos[i]=i,sum[i]=0;
        for(int i=1;i<=n;i++)
        {
            l=lower_bound(id+1,id+cnt+1,a[i].l)-id;
            r=lower_bound(id+1,id+cnt+1,a[i].r)-id;
            swap(pos[l],pos[r]);
        }
        ll ans=0;
        for(int i=1;i<=cnt;i++)
        {
            ans+=(ll)num[pos[i]]*query(pos[i]);
            add(pos[i],num[i]);
        }
        printf("%lld\n",ans);
    }
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值