Description
Mato同学从各路神犇以各种方式(你们懂的)收集了许多资料,这些资料一共有n份,每份有一个大小和一个编号。为了防止他人偷拷,这些资料都是加密过的,只能用Mato自己写的程序才能访问。Mato每天随机选一个区间[l,r],他今天就看编号在此区间内的这些资料。Mato有一个习惯,他总是从文件大小从小到大看资料。他先把要看的文件按编号顺序依次拷贝出来,再用他写的排序程序给文件大小排序。排序程序可以在1单位时间内交换2个相邻的文件(因为加密需要,不能随机访问)。Mato想要使文件交换次数最小,你能告诉他每天需要交换多少次吗?
n,q <= 50000
Solution
一开始以为是树套树的。。兴奋地码完发现做不出来
考虑分块。容易发现交换次数即是逆序对数量,用树状数组统计答案
unique和lower_bound老是记不住怎么破
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define fill(x,t) memset(x,t,sizeof(x))
#define lowbit(x) ((x)&(-(x)))
using namespace std;
const int N=100005;
const int S=250;
struct query{int l,r,id;}q[N];
int a[N],ans[N],c[N],cnt_q,n;
int b[N],rank[N],size;
int read() {
int x=0,v=1; char ch=getchar();
for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
return x*v;
}
void add(int x,int v) {
while (x<=size) {
c[x]+=v;
x+=lowbit(x);
}
}
int get(int x) {
int ret=0;
while (x) {
ret+=c[x];
x-=lowbit(x);
}
return ret;
}
int cmp1(query x,query y) {return (x.l/S<y.l/S)||(x.l/S==y.l/S&&x.r<y.r);}
int cmp2(query x,query y) {return x.id<y.id;}
int main(void) {
n=read();
rep(i,1,n) b[i]=a[i]=read();
sort(b+1,b+n+1);
size=unique(b+1,b+n+1)-b-1;
rep(i,1,n) rank[i]=lower_bound(b+1,b+size+1,a[i])-b;
int T=read();
while (T--) {q[++cnt_q]=(query){read(),read(),cnt_q};}
sort(q+1,q+cnt_q+1,cmp1);
int l=1,r=1,tot=0; add(rank[1],1);
rep(i,1,cnt_q) {
while (r<q[i].r) {
add(rank[++r],1);
tot+=get(size)-get(rank[r]);
}
while (r>q[i].r) {
tot-=get(size)-get(rank[r]);
add(rank[r--],-1);
}
while (l<q[i].l) {
tot-=get(rank[l]-1);
add(rank[l++],-1);
}
while (l>q[i].l) {
add(rank[--l],1);
tot+=get(rank[l]-1);
}
ans[q[i].id]=tot;
}
sort(q+1,q+n+1,cmp2);
rep(i,1,cnt_q) printf("%d\n", ans[i]);
return 0;
}