SSL JudgeOnline 1198——求逆序对数

来源:互联网 发布:明星淘宝店铺大全 编辑:程序博客网 时间:2024/04/30 16:03

Description

先给出逆序对的定义,对于一个给定的数列{An},如果有iAj,则称(i,j)为一逆序对.
求给出一个数列,求出这个数列包含多少个逆序对?

Input

n (<=10000)
n个数

Output

输出逆序对数?

Sample Input

Sample Output

5
3 4 2 1 3


思路一:我们用归并排序,判断如果a[i]>a[j]就ans:=ans+mid-i+1,将后面的数全部加起来

思路二:我们用两个循环1:for i:=1 to n-1 do
2:for j:=i+1 to n do
判断每一种情况,如果a[i]>a[j]就加一


代码如下:

var  a:array[1..100000]of longint;     n,ans:longint;procedure init;var i,j:longint;begin  read(n);  for i:=1 to n do read(a[i]);end;procedure move1(l,mid,r:longint);var  l1,i,j:longint;     t:array[1..100000]of longint;begin  i:=l; j:=mid+1; l1:=0;  while (i<=mid)and(j<=r) do    if a[i]>a[j] then      begin        ans:=ans+mid+1-i;        inc(l1);        t[l1]:=a[j];        inc(j);      end    else      begin        inc(l1);        t[l1]:=a[i];        inc(i);      end;  for i:=i to mid do    begin      inc(l1);      t[l1]:=a[i];    end;  for i:=j to r do    begin      inc(l1);      t[l1]:=a[i];    end;  for i:=l to r do a[i]:=t[i-l+1];end;procedure move(l,r:longint);begin  if l>=r then exit;  move(l,(l+r) div 2);  move((l+r) div 2+1,r);  move1(l,(l+r) div 2,r);end;var i:longint;begin  init;  move(1,n);  write(ans);end.
1 0
原创粉丝点击