Codeforces-540E.Infinite Inversions區間化點求交換逆序對(離散化+樹狀數組)

E. Infinite Inversions

time limit per test            memory limit per test

2 seconds                       256 megabytes

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


題目大意:給你一個1到n的序列,然後給你m次位置的交換,問你最終有幾對逆序對。。。。剛開始還以爲要把每次交換的逆序對數都回答出來。。。那麼就變成了動態逆序對的位置交換了我之前的這篇博客就有分塊處理的動態逆序對,但它的n太大了。。。。所以就不會了QAQ。。。。實際上仔細看題目就會知道,他只要求最後求一次逆序對就好了,那麼也就是說我們可以開心地將它離散化,區間化點(就是將一個區間轉化成一個點,然後這個點保留着這個區間的區間長度)就可以直接一邊插入數一邊求逆序對了(這裏的數據較小map離散化就可以過了。。。之前的一題就不行這是更噁心的離散化+線段樹Codeforces-915E,也安利一波我的博客qwq)

以下是AC代碼:

#include <bits/stdc++.h>
using namespace std;

#define ll long long

const int mac=1e5+10;

struct node
{
    int l,r;
}a[mac];
int b[mac<<2],c[mac<<2],tree[mac<<2],tot=0;
int len[mac<<2];

unordered_map<int,int>q;

void in(int &x)
{
    int f=0;
    char ch=getchar();
    while (ch>'9' || ch<'0') ch=getchar();
    while (ch>='0' && ch<='9') f=(f<<3)+(f<<1)+ch-'0',ch=getchar();
    x=f;
}

int lowbit(int x) {return x&-x;}

void update(int pos,int val)
{
    while (pos<=tot){
        tree[pos]+=val;
        pos+=lowbit(pos);
    }
}

int query(int pos)
{
    int sum=0;
    while (pos){
        sum+=tree[pos];
        pos-=lowbit(pos);
    }
    return sum;
}

int main()
{
    int n,cnt=0;
    scanf ("%d",&n);
    for (int i=1; i<=n; i++){
        int l,r;
        in(l);in(r);
        a[i].l=l;a[i].r=r;
        b[++cnt]=l;b[++cnt]=r;
    }
    sort(b+1,b+1+cnt);
    int p=b[1];
    c[1]=1;tot=1;q[b[1]]=1;len[1]=1;
    for (int i=2; i<=cnt; i++){
        if (b[i]!=p) {
            if (b[i]!=b[i-1]+1) c[++tot]=tot,len[tot]=b[i]-b[i-1]-1;
            p=b[i];
            q[b[i]]=++tot;
            c[tot]=tot;
            len[tot]=1;
        }
    }
    for (int i=1; i<=n; i++) swap(c[q[a[i].l]],c[q[a[i].r]]);
    ll ans=0,qsum=0;
    for (int i=1; i<=tot; i++){
        ans+=(qsum-query(c[i]-1))*len[i];
        qsum+=len[i];
        update(c[i],len[i]);
    }
    printf ("%lld\n",ans);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章