给定一个序列,每次询问一个区间,你可以交换相邻两个元素,这个区间你最少需要多少次交换才能使其有序。
我们观察,每次交换如果交换a[i]和a[i+1],那么显然a[i]>a[i+1],交换后逆序对个数减一。当序列逆序对个数为0时序列就有序。那么显然题意就是询问区间逆序对个数。我们可以用莫队算法来做。因为它符合类似+1-1的性质。
#include<cstdio>
#include<algorithm>
#include<cmath>
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
const int maxn=50000+10;
int tree[maxn*5],belong[maxn],a[maxn],b[maxn],ans[maxn];
struct dong{
int l,r,id;
};
dong ask[maxn];
int i,j,k,l,r,t,n,m,c,now,top;
bool cmp(dong a,dong b){
if (belong[a.l]<belong[b.l]) return 1;
else if (belong[a.l]==belong[b.l]&&a.r<b.r) return 1;
else return 0;
}
void change(int p,int l,int r,int a,int b){
if (l==r){
tree[p]+=b;
return;
}
int mid=(l+r)/2;
if (a<=mid) change(p*2,l,mid,a,b);else change(p*2+1,mid+1,r,a,b);
tree[p]=tree[p*2]+tree[p*2+1];
}
int query(int p,int l,int r,int a,int b){
if (a>b) return 0;
if (l==a&&r==b) return tree[p];
int mid=(l+r)/2;
if (b<=mid) return query(p*2,l,mid,a,b);
else if (a>mid) return query(p*2+1,mid+1,r,a,b);
else return query(p*2,l,mid,a,mid)+query(p*2+1,mid+1,r,mid+1,b);
}
int main(){
freopen("3289.in","r",stdin);freopen("3289.out","w",stdout);
scanf("%d",&n);
fo(i,1,n) scanf("%d",&a[i]),b[i]=a[i];
sort(b+1,b+n+1);
top=unique(b+1,b+n+1)-b-1;
fo(i,1,n) a[i]=lower_bound(b+1,b+top+1,a[i])-b;
scanf("%d",&m);
fo(i,1,m){
scanf("%d%d",&ask[i].l,&ask[i].r);
ask[i].id=i;
}
c=floor(sqrt(n)+1);
fo(i,1,n) belong[i]=(i-1)/c+1;
sort(ask+1,ask+m+1,cmp);
l=r=1;
change(1,1,top,a[1],1);
fo(i,1,m){
while (l<ask[i].l){
now-=query(1,1,top,1,a[l]-1);
change(1,1,top,a[l],-1);
l++;
}
while (l>ask[i].l){
l--;
now+=query(1,1,top,1,a[l]-1);
change(1,1,top,a[l],1);
}
while (r<ask[i].r){
r++;
now+=query(1,1,top,a[r]+1,top);
change(1,1,top,a[r],1);
}
while (r>ask[i].r){
now-=query(1,1,top,a[r]+1,top);
change(1,1,top,a[r],-1);
r--;
}
ans[ask[i].id]=now;
}
fo(i,1,m) printf("%d\n",ans[i]);
fclose(stdin);fclose(stdout);
return 0;
}