您的位置:首页 > 其它

BZOJ3289[Mato的文件管理]

2017-07-21 20:53 204 查看
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

n,q <= 50000

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

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

solution:分块+莫队+树状数组

这种做法的时间复杂度o(nlogn)

/**************************************************************
Problem: 3289
User: Venishel
Language: C++
Result: Accepted
Time:5464 ms
Memory:3256 kb
****************************************************************/

#include <cmath>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
#define N 50005
#define l_ad for ( ; l < q[i].l; l++ )
#define l_ms for ( ; l > q[i].l; ) l--,
#define r_ad for ( ; r < q[i].r; ) r++,
#define r_ms for ( ; r > q[i].r; r-- )
int n, m, now;
int a
, disc
, bl
, t
, ans
;
struct E{ int l, r, id; }q
;
struct P{ int v, p; }cn
;
bool operator<( E a, E b){
if ( bl[ a.l ] == bl[ b.l ] ) return a.r < b.r;
return bl[ a.l ] < bl[ b.l ];
}

bool operator<( P a, P b ){
return a.v < b.v;
}
inline void add(int x,int v ){
for(int i = x; i <= n; i += i&-i )
t[i] += v;
}
inline int query( int x ){
int sum = 0;
for(int i = x; i; i -= i&-i )
sum += t[i];
return sum;
}
inline void solve(){
sort( q+1, q+m+1 );
int l = 1, r = 0;
for(int i = 1; i <= m; i++){
l_ad add( a[l], -1 ), now -= query( a[l]-1 );
l_ms add( a[l], 1 ), now += query( a[l]-1 );
r_ad add( a[r], 1 ), now += r - l + 1 - query( a[r] );
r_ms add( a[r], -1 ), now -= r - l - query( a[r] );
ans[ q[i].id ]=now;
}
}
int main(){
n = read();
int t = sqrt(n);
for(int i = 1 ; i <= n; i++) cn[i].v = a[i] = read(), cn[i].p = i;
sort( cn+1, cn+1+n );
for ( int i = 1; i <= n; i++ ) a[ cn[i].p ] = i;
m = read();
for(int i = 1 ; i <= m; i++)
q[i].l = read(), q[i].r = read(), q[i].id = i;
for(int i = 1 ; i <= n; i++)
bl[i] = ( i - 1) / t + 1;
solve();
for(int i = 1 ; i <= m; i++)
printf( "%d\n", ans[i]);
return 0;
}

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