P1908 逆序对

    xiaoxiao2021-03-26  24

    题目描述

    猫猫TOM和小老鼠JERRY最近又较量上了,但是毕竟都是成年人,他们已经不喜欢再玩那种你追我赶的游戏,现在他们喜欢玩统计。最近,TOM老猫查阅到一个人类称之为“逆序对”的东西,这东西是这样定义的:对于给定的一段正整数序列,逆序对就是序列中ai>aj且i<j的有序对。知道这概念后,他们就比赛谁先算出给定的一段正整数序列中逆序对的数目。

    输入输出格式

    输入格式:

    第一行,一个数n,表示序列中有n个数。

    第二行n个数,表示给定的序列。

    输出格式:

    给定序列中逆序对的数目。

    输入输出样例

    输入样例#1: 6 5 4 2 6 3 1 输出样例#1: 11

    说明

    对于50%的数据,n≤2500

    对于100%的数据,n≤40000。

    const maxn=100000;var a,b:array[1..maxn] of longint; n,i:longint; ans:int64;function count(l,r:longint):longint;var m,i,j,k:longint;begin if l=r then exit; m:=(l+r) shr 1; count(l,m);count(m+1,r); i:=l;j:=m+1;k:=l-1; while (i<=m)and(j<=r) do begin while (a[i]<=a[j])and(i<=m) do begin inc(k); b[k]:=a[i]; if j<=r then inc(ans,j-m-1); inc(i); end; while (a[i]>a[j])and(j<=r) do begin inc(k); b[k]:=a[j]; inc(j); end; end; while i<=m do begin inc(k); b[k]:=a[i]; inc(ans,j-m-1); inc(i); end; for i:=l to j-1 do a[i]:=b[i];end;begin readln(n); for i:=1 to n do read(a[i]); count(1,n); writeln(ans);end.

    转载请注明原文地址: https://ju.6miu.com/read-662380.html

    最新回复(0)