BZOJ 3289: Mato的文件管理 莫队算法

xiaoxiao2021-02-28  108

Time Limit: 40 Sec Memory Limit: 128 MB Submit: 3363 Solved: 1385

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

HINT

Hint

n,q <= 50000

样例解释:第一天,Mato不需要交换

第二天,Mato可以把2号交换2次移到最后。

Source

By taorunz


题解:

对于上一道没穿衣服的莫队来说,这一道应该算是穿了薄薄的一层衣服,我们只需要利用树状数组,就可以把这层衣服脱去,让其又成为没穿衣服的莫队 /害羞… 显然,逆序对对数就是我们要求的个数,所以只需要动态地维护逆序对对数就可以了


/************************************************************** Problem: 3289 User: cdqz_hhl Language: C++ Result: Accepted Time:5668 ms Memory:2868 kb ****************************************************************/ #include<cstdio> #include<cstring> #include<iostream> #include<cmath> #include<algorithm> const int MAXN=50005; using namespace std; struct Question{ int l,r,id,loc,ans; }q[MAXN]; int n,m,C[MAXN],after[MAXN],len,b[MAXN]; bool cmp(const Question& A,const Question& B){ if(A.loc==B.loc) return A.r<B.r; else return A.loc<B.loc; } int lowbit(int x){return x&(-x);} void add(int x,int val){ while(x<=n){ C[x]+=val; x+=lowbit(x); } } int query(int loc){ int sum=0; while(loc){ sum+=C[loc]; loc-=lowbit(loc); } return sum; } void solve(){ sort(q+1,q+m+1,cmp); int l=1,r=0,temp=0; for(register int i=1;i<=m;i++){ while(l<q[i].l) add(after[l],-1),temp-=query(after[l]-1),l++; //因为l是最左端,所以减的应该是当前的比这个数小的数的个数 while(r>q[i].r) add(after[r],-1),temp-=r-l-query(after[r]-1),r--; //因为r是最右端,其中r-l是现在的新区间大小(也就是r--之后),新区间大小减去这里面的小于after[r]的数 while(l>q[i].l) l--,add(after[l],1),temp+=query(after[l]-1); //与第一个while同理 while(r<q[i].r) r++,add(after[r],1),temp+=r-l+1-query(after[r]); //如果当前的r小于询问的r,那么r++,新的区间大小是r-l+1,要查询到所有小于等于r的个数为query(after[r]),那么所有大于after[r]的数纪委r-l+1-query(after[r]); q[q[i].id].ans=temp; } } int main(){ scanf("%d",&n);len=sqrt(n); for(register int i=1;i<=n;i++) scanf("%d",&b[i]),after[i]=b[i]; sort(b+1,b+n+1); for(register int i=1;i<=n;i++) after[i]=lower_bound(b+1,b+n+1,after[i])-b; //数据离散化 scanf("%d",&m); for(register int i=1;i<=m;i++){ scanf("%d%d",&q[i].l,&q[i].r);q[i].id=i;q[i].loc=(q[i].l-1)/len+1; } solve(); for(register int i=1;i<=m;i++) printf("%d\n",q[i].ans); return 0; }
转载请注明原文地址: https://www.6miu.com/read-59417.html

最新回复(0)