import java lang String import static java lang System import java uti

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
import java.lang.String.*;
import static java.lang.System.*;
import java.util.*;
import java.math.BigInteger;
class QuickSort
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++)
arr[i] = in.nextInt();
long l = quicksort(arr);
/*for (int i = 0; i < N; i++)
System.out.print(arr[i] + " ");
System.out.println();*/
System.out.println(l);
}
static long quicksort(int[] arr)
{
return quicksort(arr, 0, arr.length - 1);
}
static long quicksort(int[] arr, int start, int end)
{
long l = 0L;
if (end - start + 1 <= 1)
return l;
int p = partition(arr, start, end);
l += end - start;
l += quicksort(arr, start, p - 1);
l += quicksort(arr, p + 1, end);
return l;
}
static void swap(int[] arr, int a, int b)
{
int x = arr[a];
arr[a] = arr[b];
arr[b] = x;
return;
}
static int min(int a, int b)
{
return a < b ? a : b;
}
static int max(int a, int b)
{
return a > b ? a : b;
}
static int med(int a, int b, int c)
{
int mx = max(max(a, b), c);
int mn = min(min(a, b), c);
return a ^ b ^ c ^ mx ^ mn;
}
static int partition(int[] arr, int start, int end)
{
int p, median;
if ((end - start + 1 ) % 2 == 0)
median = (end - start + 1) / 2;
else median = (end - start + 1) / 2 + 1;
int x = med(arr[start], arr[median], arr[end]);
if (x == arr[start])
p = start;
else
if (x == arr[median])
p = median;
else
p = end;
swap(arr, p, start);
p = start;
int i = start + 1;
int j = start + 1;
for (; j <= end; j++)
{
if (arr[j] < arr[p])
{
swap(arr, i, j);
i++;
}
}
swap(arr, i - 1, p);
return i - 1;
}
}