[題解]bzoj3289 Mato的文件管理

Description

Mato同學從各路神犇以各種方式(你們懂的)收集了許多資料,這些資料一共有n份,每份有一個大小和一個編號。爲了防止他人偷拷,這些資料都是加密過的,只能用Mato自己寫的程序才能訪問。Mato每天隨機選一個區間[l,r],他今天就看編號在此區間內的這些資料。Mato有一個習慣,他總是從文件大小從小到大看資料。他先把要看的文件按編號順序依次拷貝出來,再用他寫的排序程序給文件大小排序。排序程序可以在1單位時間內交換2個相鄰的文件(因爲加密需要,不能隨機訪問)。Mato想要使文件交換次數最小,你能告訴他每天需要交換多少次嗎?

Input

第一行一個正整數n,表示Mato的資料份數。
第二行由空格隔開的n個正整數,第i個表示編號爲i的資料的大小。
第三行一個正整數q,表示Mato會看幾天資料。
之後q行每行兩個正整數l、r,表示Mato這天看[l,r]區間的文件。

Output

q行,每行一個正整數,表示Mato這天需要交換的次數。

Sample Input

4
1 4 2 3
2
1 2
2 4

Sample Output

0
2

Solution

此題就是求區間逆序對數量。莫隊,用樹狀數組O(log2n) 轉移,就是查詢區間新加的那個數(或者減少的那個數)在區間內貢獻的逆序對數量。
複雜度O(nnlog2n)

代碼:

#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

typedef long long LL;
const int maxn=50010;
struct Q{
    int l,r,id;
    LL a;
}q[maxn];
int B,block[maxn],n,m,cnt,a[maxn],rnk[maxn];
LL ans;
struct Bit{
    int a[maxn];
    Bit(){memset(a,0,sizeof a);}
    void Add(int x,int val){
        for(;x<=cnt;x+=(x&-x))a[x]+=val;
    }
    LL Query(int x){
        LL res=0;
        for(;x;x-=(x&-x))res+=a[x];
        return res;
    }
}bit;

bool comp(Q x,Q y){
    if(block[x.l]==block[y.l])return x.r<y.r;
    return x.l<y.l;
}
bool comp_id(Q x,Q y){
    return x.id<y.id;
}
void update(int x,int add,bool f){
    int temp=f?(bit.Query(cnt)-bit.Query(a[x])):bit.Query(a[x]-1);
    if(add>0)ans+=temp;
    else ans-=temp;
    bit.Add(a[x],add);
}

int main(){
    scanf("%d",&n);B=(int)sqrt(n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        rnk[i]=a[i];
        block[i]=(i-1)/B+1;
    }
    sort(rnk+1,rnk+n+1);
    cnt=unique(rnk+1,rnk+n+1)-rnk-1;
    for(int i=1;i<=n;i++)a[i]=lower_bound(rnk+1,rnk+cnt+1,a[i])-rnk;
    scanf("%d",&m);
    for(int i=1;i<=m;i++)
        scanf("%d%d",&q[i].l,&q[i].r),q[i].id=i;
    sort(q+1,q+m+1,comp);
    for(int i=1,l=1,r=0;i<=m;i++){
        while(r<q[i].r)update(++r,1,1);
        while(r>q[i].r)update(r--,-1,1);
        while(l<q[i].l)update(l++,-1,0);
        while(l>q[i].l)update(--l,1,0);
        q[i].a=ans;
    };
    sort(q+1,q+m+1,comp_id);
    for(int i=1;i<=m;i++)printf("%lld\n",q[i].a);
    return 0;
}
發佈了81 篇原創文章 · 獲贊 43 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章