题意:给定一个序列,每次选择一个位置,把这个位置之后所有不大于这个数的数抽出来,排序,再插回去,求每次操作后的逆序对数
对于我们每次选择的位置p,无论怎么操作,都不会对位置p之前的数的逆序对造成影响,也不会对[p,n]中大于a[p]的数的逆序对造成影响
同时很容易发现,没进行一次操作逆序对数都是只减不增的
所以我们能够得到一个结论:每次答案会减去参加重新的排序的数形成的逆序对数
而且很容易发现,我们的挑数、排序、插回的操作,对于当前需要处理的位置i来说,实质上就是a[i]和[i,n]中的最小值交换位置
那么就用线段树维护区间最小值就ok啦
那么实现方法就很明确了:
树状数组维护f[i]:表示[i,n]中的逆序对数;
线段树维护区间最小值,每找到当前区间最小值tt及它的位置pos,就在ans中减去f[pos],同时在线段树里把它的值更新为正无穷(可以保证每个数只会被找到一次),重复上述操作直到当前区间的最小值为a[p]
均摊复杂度O(nlogn)
type
rec2=record
num,pos:longint;
end;
type
rec=record
l,r:longint;
minn:rec2;
end;
var
a :array[0..500010] of longint;
_t,f :array[0..500010] of int64;
flag :array[0..500010] of boolean;
b :array[0..500010] of rec2;
t :array[0..1500010] of rec;
ans :int64;
tt :rec2;
n,m,p :longint;
i :longint;
procedure _add(x,v:longint);
begin
while x<=n do
begin
inc(_t[x],v);
inc(x,x and (-x));
end;
end;
function find2(x:longint):int64;
var
ans:int64;
begin
ans:=0;
while x>0 do
begin
inc(ans,_t[x]);
dec(x,x and (-x));
end;
exit(ans);
end;
procedure sort(l,r:longint);
var
i,j,x:longint;
y:rec2;
begin
i:=l; j:=r; x:=b[(l+r)>>1].num;
while i<=j do
begin
while b[i].numx do dec(j);
if i<=j then
begin
y:=b[i]; b[i]:=b[j]; b[j]:=y;
inc(i); dec(j);
end;
end;
if il then sort(l,j);
end;
procedure lsh;
var
i,tot:longint;
begin
for i:=1 to n do
begin
b[i].num:=a[i]; b[i].pos:=i;
end;
sort(1,n);
tot:=1; a[b[1].pos]:=1;
for i:=2 to n do
begin
if b[i].num<>b[i-1].num then inc(tot);
a[b[i].pos]:=tot;
end;
end;
procedure build(x,l,r:longint);
var
mid:longint;
begin
t[x].l:=l; t[x].r:=r;
if l=r then
begin
t[x].minn.num:=a[l]; t[x].minn.pos:=l; exit;
end;
mid:=(l+r)>>1;
build(x<<1,l,mid);
build((x<<1)+1,mid+1,r);
if t[x<<1].minn.num>1;
if y<=mid then change(x<<1,y,z) else change((x<<1)+1,y,z);
if t[x<<1].minn.num>1;
if r<=mid then exit(find(x<<1,l,r)) else
if l>mid then exit(find((x<<1)+1,l,r)) else
begin
t1:=find(x<<1,l,mid);
t2:=find((x<<1)+1,mid+1,r);
if t1.nump do
begin
if not flag[tt.pos] then
begin
flag[tt.pos]:=true;
dec(ans,f[tt.pos]);
end;
change(1,tt.pos,maxlongint);
tt:=find(1,p,n);
end;
flag[p]:=true;
dec(ans,f[p]);
end;
writeln(ans);
end;
end.
——by Eirlys