您的位置:首页 > 其它

[Bzoj3289]Mato的文件管理(莫队 + 树状数组)

2017-10-12 09:27 281 查看

3289: Mato的文件管理

 

Time Limit: 40 Sec  Memory Limit: 128 MB
Submit: 3681  Solved: 1496
[Submit][Status][Discuss]

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次移到最后。

 

分析:

    首先很快分析出 两两交换有序的最少次数为求一个区间内逆序对的个数。再看看题上只有区间查询,想到莫队算法 + 树状数组(线段树也可以)维护逆序对数。

    树状数组离散化数字大小后从小到大排序。当前(l,r)比如后面进来一个数(r + 1),然后在(r +1)所代表数在树状数组位置+1,多的逆序对个数即为查询(l,r)里比它大的数。可以用(r - l + 1) + Query(a[r + 1]),Query查询出来的值为(l,r)里比(r + 1)下标所在位置的数小的数的个数。

    删除也同理。莫队维护一下就行了。

   莫队算法可以见我的http://www.cnblogs.com/lzdhydzzh/p/7651588.html一些讲解。

贴上AC代码:

 

 

# include <iostream>
# include <cstdio>
# include <cmath>
# include <algorithm>
using namespace std;
const int N = 1e5;
int b
,a
,n,m,block
,tot;
long long sum
,ans
;
int lowbit(int k){return k & -k;}
struct data{
int l,r,id;
bool operator <(const data & other)const{
if(block[l] == block[other.l])return r < other.r;
return block[l] < block[other.l];
}
}q
;
void updata(int k,long long val){
while(k <= n){
sum[k] += val;
k += lowbit(k);
}
}
long long Query(int k){
long long ans = 0LL;
while(k){
ans += sum[k];
k -= lowbit(k);
}
return ans;
}
void Modui(){
int l = 1,r = 0;
long long num = 0;
for(int i = 1;i <= m;i++){
while(r < q[i].r)r++,updata(a[r],1LL),num += r - l + 1 - Query(a[r]);
while(r > q[i].r)updata(a[r],-1LL),num -= r - l - Query(a[r]),r--;
while(l < q[i].l)updata(a[l],-1LL),num -= Query(a[l] - 1),l++;
while(l > q[i].l)l--,updata(a[l],1LL),num += Query(a[l] - 1);
ans[q[i].id] = num;
}
}
int main(){
scanf("%d",&n);tot = sqrt(n);
for(int i = 1;i <= n;i++){
scanf("%d",&a[i]);
b[i] = a[i];block[i] = i / tot + 1;
}
sort(b + 1,b + n + 1);
for(int i = 1;i <= n;i++)a[i] = lower_bound(b + 1,b + n + 1,a[i]) - b;
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);
Modui();
for(int i = 1;i <= m;i++){
printf("%lld\n",ans[i]);
}
return 0;
}

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: