LearnToCP
Sign in
Navigation
HomeRoadmapProblemsAbout Us
Theory
Contest Knowledge
Selecting an IDEInteractive TasksOutput-Only Tasks
Basics
Your First ProgramData types and IOC++ syntaxModuloFunctionsVectorsMatricesTime Complexity
Sorting
SortingCounting sortRadix Sort
Optimization Techniques
Two PointersSum of numbers 1 to nPrefix sumBinary SearchGreedyBinary Search FunctionsBinary Search by AnswerDivide and Conquer
Binary Numbers
Binary NumbersNumbers in codeBitwise OperationsBitmasks
Math
Binary ExponentiationPrime NumbersPrime FactorizationGCD and LCMSieve of EratosthenesModified Sieve
Data Structures
StringsStackQueueMapsSetsPriority QueueCustom Criteria for FunctionsSegment TreesFenwick TreesSparse TablesUnion FindSqrt Decomposition
Combinatorics
Addition PrincipleMultiplication PrincipleCombinatoric ObjectsInclusion Exclusion Principle
Geometry
Geometry BasicsVectorsCross and Dot ProductLinesPolygonsAnglesPoint in PolygonDistances and Intersection PointsConvex HullCircles
Recursion
PointersRecursionGenerating Combinatoric Objects
Dynamic Programming
About DPDP problemsTree DPBitmask DP
Graph Theory
GraphsDFS and BFSShortest PathsTreesTopological SortingDijkstra's AlgorithmMinimum Spanning TreesShortest Path Algorithms
Advanced Graph Theory
BiconnectivityStrongly Connected ComponentsBipartite GraphGraph FlowAugmenting PathsFlow - Minimum Cut DualityHeavy-Light DecompositionCentroid Decomposition
Advanced Data Structures
2D and 3D Segment TreesLazy PropagationImplicit Segment TreesPersistent Segment TreesLowest Common AncestorTrieBalanced Binary Search TreesMo's Algorithm

Number of Inversions

MediumProblem #60
Time LimitMemoryInputOutput
1 s64 MBstdinstdout

Counting the pairs one by one is too slow. Watch the size of the answer.

An inversion in an array is a pair of positions i<j where the earlier element is the bigger one, that is ai​>aj​. A sorted array has no inversions at all, and an array sorted the wrong way round has as many as there are pairs - so the number of inversions is a measure of how far from sorted an array is.

Your task is to count them.

Input

First line of input will be a single integer t - the number of testcases.
The first line of each testcase contains a single integer n - the length of the array.
The second line contains n integers a1​,a2​,…,an​.

Output

For every testcase print a single line with the number of inversions in that array.

Example

Input
2
5
3 1 4 2 5
4
4 3 2 1
Output
3
6

The first array has three inversions: the pairs (3,1), (3,2) and (4,2). The second one is sorted in reverse, so every one of its 6 pairs is an inversion.

Constraints

1≤t≤10
1≤n≤105
−109≤ai​≤109
The sum of n over all testcases does not exceed 2⋅105


This problem was adapted, with permission, from Broj inverzija, authored by Društvo matematičara Srbije and Fondacija Petlja.

Submit your solution

Sign in to submit your solution and track your progress.

Sign in to submit