CodeForces 785E :Anton and Permutation 二分+分块

传送门

题目描述

给定一个长度为n的排列,有q个操作,每次交换两个位置上的数。
对于每个操作,输出操作之后的逆序对数。

分析

分析一下,每次交换对逆序对产生的影响,会发现每次增加或减少的数量只会在l - r区间内产生,加上两倍l + 1 —— r - 1区间内比a[r]小的元素数量,减去 两倍l + 1 —— r - 1区间内比a[l]小的元素数量,可以用分块去维护,把每个块内的元素变成有序,然后如果查询一整个块内符合条件的元素数量就可以考虑用二分解决

代码

#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 200010;
const ll mod= 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a){
    
    char c=getchar();T x=0,f=1;while(!isdigit(c)){
    
    if(c=='-')f=-1;c=getchar();}
while(isdigit(c)){
    
    x=(x<<1)+(x<<3)+c-'0';c=getchar();}a=f*x;}
int a[N];
int p[N];
int len;
vector<int> v[N];
int n,m;
ll ans;

void modify(int l,int r){
    
    
    if(p[l] != p[r]){
    
    
        v[p[l]].erase(lower_bound(v[p[l]].begin(), v[p[l]].end(),a[l]));
        v[p[r]].erase(lower_bound(v[p[r]].begin(), v[p[r]].end(),a[r]));
        v[p[l]].insert(upper_bound(v[p[l]].begin(), v[p[l]].end(),a[r]),a[r]);
        v[p[r]].insert(upper_bound(v[p[r]].begin(), v[p[r]].end(),a[l]),a[l]);
    }
    swap(a[l],a[r]);
    return;
}

ll query(int l,int r,int x){
    
    
    ll res = 0;
    if(l > r) return 0;
    for(int i = l;p[i] == p[l] && i <= r;i++) res += (a[i] < x);
    if(p[l] == p[r]) return res;
    for(int i = r;p[i] == p[r];i--) res += (a[i] < x);
    for(int i = p[l] + 1;i < p[r];i++) res += (lower_bound(v[i].begin(), v[i].end(),x) - v[i].begin());
    return res;
}

int main(){
    
    
    read(n),read(m);
    len = sqrt(n);
    for(int i = 1;i <= n;i++) {
    
    
        a[i] = i;
        p[i] = (i - 1) / len;
        v[p[i]].push_back(i);
    }
    while(m--){
    
    
        int l,r;
        read(l),read(r);
        if(l > r) swap(l,r);
        if(l == r){
    
    
            dl(ans);
            continue;
        }
        ans = ans + 2 * (query(l + 1,r - 1,a[r]) - query(l + 1,r - 1,a[l]));
        if(a[l] < a[r]) ans++;
        else ans--;
        dl(ans);
        modify(l,r);
    }
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/


猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/113396812