题目链接
Codeforces-540E-Infinite Inversions
题意
给一个无限大的递增序列,n次操作,每次操作一组x,y,代表第x位置的数和第y位置的数进行交换,问最后n次交换后存在多少对逆序对。(n<=1e5, x,y<=1e9)
题解
离散化树状数组
x,y很大,但n很小可以通过离散化的形式来使用树状数组求逆序对。
注意到交换后两数之间未操作数也会影响到最终逆序对的个数。于是对于每一段未操作数段也进行离散化成一个点,并用数组记录数段的长度为权值。操作数的长度为1为权值。最后使用树状数组进行计数时,需要乘上其权值。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 4e5+10;
typedef struct node{
int first,second;
}point;
point store[maxn];///储存交换对
ll c[maxn];///树状数组
int index[maxn];///标记操作数数组-用于构造num数组
int num[maxn];///记录离散后存储的实际数。
int val[maxn];///记录实际数的权值
int p[maxn]; ///第i个位置为实际数的离散位置
///形象的说 p[i] = total;num[total] = x;val[total] = x的长度(权值),交换x和y相当于交换total_1和total_2。
int lowbit(int x) {return x & -x;}
void add(int pos,int x){
for(int i=pos;i<maxn;i+=lowbit(i)) c[i] += x;
}
ll sum(int pos){
ll ans = 0;
for(int i=pos;i;i-=lowbit(i)) ans += c[i];
return ans;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
int cnt = 0,total = 0;
for(int i=1;i<=n;i++) {
scanf("%d%d",&store[i].first,&store[i].second);
index[cnt++] = store[i].first;
index[cnt++] = store[i].second;
}
sort(index,index+cnt);
cnt = unique(index,index+cnt)-index;
num[++total] = index[0];val[total] = 1;///离散化
for(int i=1;i<cnt;i++) {
if(index[i] > index[i-1] + 1)
{
num[++total] = index[i-1] + 1;
val[total] = index[i] - index[i-1] - 1;
}
num[++total] = index[i];
val[total] = 1;
}
for(int i=1;i<=total;i++) p[i] = i;///构造顺序数组
for(int i=1;i<=n;i++){///模拟交换
int l = lower_bound(num+1,num+total+1,store[i].first) - num;
int r = lower_bound(num+1,num+total+1,store[i].second)- num;
swap(p[l],p[r]);
}
ll ans = 0;
for(int i=total;i>=1;i--) {
ans += (ll)val[p[i]]*sum(p[i]) ;
add(p[i],val[p[i]]);
}
printf("%I64d\n",ans);
}
return 0;
}