codeforces 840E (树状数组+离散化+缩点)

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 );
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值