procedureswap(a,b:longint);var t:longint;
beginfor i:=1to3dobegin
t:=x[a,i];
x[a,i]:=x[b,i];
x[b,i]:=t;
end;
end;
proceduresort(l,r: longint);var i,j,x1,x2,y: longint;
begin
i:=l; j:=r; x1:=x[(l+r) div2,1]; x2:=x[(l+r) div2,2];
repeatwhile (x[i,1]<x1)or((x[i,1]=x1)and(x[i,2]<x2)) do inc(i);
while (x1<x[j,1])or((x[j,1]=x1)and(x[j,2]>x2)) do dec(j);
ifnot(i>j) thenbegin
swap(i,j);
inc(i); dec(j);
end;
until i>j;
if l<j then sort(l,j);
if i<r then sort(i,r);
end;
归并排序
逆序对
var
x,y:array[0..2000000]of longint;
i,j,k:longint;
n,len:longint;
ans:int64;
proceduresort(l,r:longint);var i,j,mid:longint;
beginif l>=r thenexit;
mid:=(l+r)>>1;
sort(l,mid);
sort(mid+1,r);
i:=l; j:=mid+1; len:=l-1;
while (i<=mid)or(j<=r) doif (j>r)or((i<=mid)and(x[i]<=x[j]))
thenbegin inc(len); y[len]:=x[i]; inc(i); endelsebegin inc(len); y[len]:=x[j]; inc(j); inc(ans,mid-i+1); {inc是用来算逆序对的}end;
for i:=l to r do
x[i]:=y[i];
end;
begin
readln(N);
for i:=1to n doread(x[i]);
ans:=0;
sort(1,n);
writeln(ans);
end.
树状数组
先离散化,从后向前每次先查询,再把自己加入树状数组
加入时是把y[x[i]]+1
var
x,y:array[0..1000005]of longint;
i,j,k:longint;
n,maxn:longint;
ans:int64;
functionquery(a:longint):int64;
var tt:int64;
begin
tt:=0;
while a>0dobegin
inc(tt,y[a]);
dec(a,a and(-a));
end;
exit(tt);
end;
procedureupdate(a:longint);beginwhile a<=maxn dobegin
inc(y[a]);
inc(a,a and(-a));
end;
end;
begin
readln(n); maxn:=0;
for i:=1to n dobeginread(x[i]); if x[i]>maxn then maxn:=x[i]; end;
ans:=0;
for i:=n downto1dobegin
inc(ans,query(x[i]-1));
update(x[i]);
end;
writeln(ans);
end.
堆排序
var
n,i:longint;
x,heap:array[0..1000000]of longint;
procedureshai(z:longint);var tt,a,b,s:longint;
begin
tt:=z;
while (heap[tt*2]<>-maxlongint)or(heap[tt*2+1]<>-maxlongint) dobegin
a:=tt*2; b:=a+1;
if (heap[a]>heap[tt])and(heap[a]>=heap[b]) thenbegin s:=heap[a]; heap[a]:=heap[tt]; heap[tt]:=s; tt:=a; endelseif (heap[b]>heap[tt])and(heap[b]>=heap[a]) thenbegin s:=heap[b]; heap[b]:=heap[tt]; heap[tt]:=s; tt:=b; endelsebreak;
end;
end;
procedureprepare;begin
readln(n);
for i:=1to5*n do
heap[i]:=-maxlongint;
for i:=1to n doread(heap[i]);
end;
begin
prepare;
heap[0]:=n;
for i:=(n div2) downto1do
shai(i);
while heap[0]<>1dobegin
inc(x[0]); x[x[0]]:=heap[1];
dec(heap[0]); heap[1]:=0; shai(1);
end;
x[n]:=heap[1];
for i:=n downto2dowrite(x[i],' ');
writeln(x[1]);
end.
双关键字快排function swap(a,b:longint);var t:longint;begin for i:=1 to 3 do begin t:=x[a,i]; x[a,i]:=x[b,i]; x[b,i]:=t; end;end;procedure sort(l,r: longint);var i,j,x1,x2,y: longint;begin