Sunday, January 29, 2012

UVa_00531_Compromise.java

Problem Links:

uva00531, zoj1939,

Problem:


  Compromise 

In a few months the European Currency Union will become a reality. However, to join the club, the Maastricht criteria must be fulfilled, and this is not a trivial task for the countries (maybe except for Luxembourg). To enforce that Germany will fulfill the criteria, our government has so many wonderful options (raise taxes, sell stocks, revalue the gold reserves,...) that it is really hard to choose what to do.

Therefore the German government requires a program for the following task:

Two politicians each enter their proposal of what to do. The computer then outputs the longest common subsequence of words that occurs in both proposals. As you can see, this is a totally fair compromise (after all, a common sequence of words is something what both people have in mind).

Your country needs this program, so your job is to write it for us.

Input Specification 

The input file will contain several test cases.
Each test case consists of two texts. Each text is given as a sequence of lower-case words, separated by whitespace, but with no punctuation. Words will be less than 30 characters long. Both texts will contain less than 100 words and will be terminated by a line containing a single '#'.
Input is terminated by end of file.

Output Specification 

For each test case, print the longest common subsequence of words occuring in the two texts. If there is more than one such sequence, any one is acceptable. Separate the words by one blank. After the last word, output a newline character.

Sample Input 

die einkommen der landwirte
sind fuer die abgeordneten ein buch mit sieben siegeln
um dem abzuhelfen
muessen dringend alle subventionsgesetze verbessert werden
#
die steuern auf vermoegen und einkommen
sollten nach meinung der abgeordneten
nachdruecklich erhoben werden
dazu muessen die kontrollbefugnisse der finanzbehoerden
dringend verbessert werden
#

Sample Output 

die einkommen der abgeordneten muessen dringend verbessert werden



Source Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Problem: 531, Compromise.
 * Using Longest Common Subsequence.
 */

/**
 * @author antonio081014
 * @since Jan 29, 2012, 4:55:25 PM
 */
class Main {

    public static List<String> listA;
    public static List<String> listB;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String strLine;
        for (int t = 0;; t++) {
            strLine = br.readLine();
            if (strLine == null || strLine.length() == 0
                    || strLine.compareTo("#") == 0)
                break;
            listA = new ArrayList<String>();
            listB = new ArrayList<String>();

            while (strLine.compareTo("#") != 0) {
                String[] strs = strLine.split("\\s");
                for (int i = 0; i < strs.length; i++)
                    listB.add(strs[i]);
                strLine = br.readLine();
            }
            do {
                strLine = br.readLine();
                String[] strs = strLine.split("\\s");
                for (int i = 0; i < strs.length; i++)
                    listA.add(strs[i]);
            } while (strLine.compareTo("#") != 0);
            print(LCS());
        }
    }

    public static int[][] LCS() {
        int N = listA.size();
        int M = listB.size();
        int[][] dp = new int[N + 1][M + 1];
        int[][] parent = new int[N + 1][M + 1];

        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= M; j++) {
                if (listA.get(i - 1).compareTo(listB.get(j - 1)) == 0) {
                    dp[i][j] = 1 + dp[i - 1][j - 1];
                    parent[i][j] = 1;
                }
                else {
                    dp[i][j] = dp[i - 1][j];
                    parent[i][j] = 2;
                    if (dp[i][j - 1] > dp[i - 1][j]) {
                        dp[i][j] = dp[i][j - 1];
                        parent[i][j] = 3;
                    }
                }
            }
        }
        return parent;
    }

    public static void print(int[][] parent) {
        List<String> list = new ArrayList<String>();
        for (int i = listA.size(), j = listB.size(); i > 0 && j > 0;) {
            if (parent[i][j] == 1) {
                list.add(listA.get(i - 1));
                i--;
                j--;
            }
            else {
                if (parent[i][j] == 2)
                    i--;
                else if (parent[i][j] == 3)
                    j--;
            }
        }
        for (int i = list.size() - 1; i > 0; i--)
            System.out.print(list.get(i) + " ");
        System.out.println(list.get(0));
    }
}

UVa_10192_Vacation.java

Problem Links:

uva10192,

Problem:


 Problem E: Vacation 

The Problem

You are planning to take some rest and to go out on vacation, but you really don't know which cities you should visit. So, you ask your parents for help. Your mother says "My son, you MUST visit Paris, Madrid, Lisboa and London. But it's only fun in this order." Then your father says: "Son, if you're planning to travel, go first to Paris, then to Lisboa, then to London and then, at last, go to Madrid. I know what I'm talking about."
Now you're a bit confused, as you didn't expected this situation. You're afraid that you'll hurt your mother if you follow your father's suggestion. But you're also afraid to hurt your father if you follow you mother's suggestion. But it can get worse, because you can hurt both of them if you simply ignore their suggestions!
Thus, you decide that you'll try to follow their suggestions in the better way that you can. So, you realize that the "Paris-Lisboa-London" order is the one which better satisfies both your mother and your father. Afterwards you can say that you could not visit Madrid, even though you would've liked it very much.
If your father have suggested the "London-Paris-Lisboa-Madrid" order, then you would have two orders, "Paris-Lisboa" and "Paris-Madrid", that would better satisfy both of your parent's suggestions. In this case, you could only visit 2 cities.
You want to avoid problems like this one in the future. And what if their travel suggestions were bigger? Probably you would not find the better way very easy. So, you decided to write a program to help you in this task. You'll represent each city by one character, using uppercase letters, lowercase letters, digits and the space. Thus, you can have at most 63 different cities to visit. But it's possible that you'll visit some city more than once.
If you represent Paris with "a", Madrid with "b", Lisboa with "c" and London with "d", then your mother's suggestion would be "abcd" and you father's suggestion would be "acdb" (or "dacb", in the second example).
The program will read two travel sequences and it must answer how many cities you can travel to such that you'll satisfy both of your parents and it's maximum.

The Input

The input will consist on an arbitrary number of city sequence pairs. The end of input occurs when the first sequence starts with an "#"character (without the quotes). Your program should not process this case. Each travel sequence will be on a line alone and will be formed by legal characters (as defined above). All travel sequences will appear in a single line and will have at most 100 cities.

The Output

For each sequence pair, you must print the following message in a line alone:
Case #d: you can visit at most K cities.
Where d stands for the test case number (starting from 1) and K is the maximum number of cities you can visit such that you'll satisfy both you father's suggestion and you mother's suggestion.

Sample Input

abcd
acdb
abcd
dacb
#

Sample Output

Case #1: you can visit at most 3 cities.
Case #2: you can visit at most 2 cities.

© 2001 Universidade do Brasil (UFRJ). Internal Contest Warmup 2001.


Source Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * UVA Problem: 10192, Vacation.
 *
 */

/**
 * @author antonio081014
 * @since Jan 29, 2012, 2:34:19 PM
 */
class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String strA;
        String strB;
        for (int t = 1;; t++) {
            strA = br.readLine();
            if (strA.compareTo("#") == 0)
                break;
            strB = br.readLine();
            System.out.println(String.format(
                    "Case #%d: you can visit at most %d cities.", t,
                    LCS(strA, strB)));
        }
    }

    public static int LCS(String a, String b) {
        int M = b.length();
        int N = a.length();
        int[][] dp = new int[N + 1][M + 1];
        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= M; j++) {
                if (a.charAt(i - 1) == b.charAt(j - 1)) {
                    dp[i][j] = Math.max(dp[i][j], 1 + dp[i - 1][j - 1]);
                }
                else {
                    dp[i][j] = Math.max(dp[i][j],
                            Math.max(dp[i - 1][j], dp[i][j - 1]));
                }
            }
        }
        return dp[N][M];
    }
}

Saturday, January 28, 2012

UVa_00111_History_Grading.java

Problem Links:

uva00111,

Problem:



 History Grading 

Background

Many problems in Computer Science involve maximizing some measure according to constraints.
Consider a history exam in which students are asked to put several historical events into chronological order. Students who order all the events correctly will receive full credit, but how should partial credit be awarded to students who incorrectly rank one or more of the historical events?
Some possibilities for partial credit include:
  1. 1 point for each event whose rank matches its correct rank
  2. 1 point for each event in the longest (not necessarily contiguous) sequence of events which are in the correct order relative to each other.
For example, if four events are correctly ordered 1 2 3 4 then the order 1 3 2 4 would receive a score of 2 using the first method (events 1 and 4 are correctly ranked) and a score of 3 using the second method (event sequences 1 2 4 and 1 3 4 are both in the correct order relative to each other).
In this problem you are asked to write a program to score such questions using the second method.

The Problem

Given the correct chronological order of n events tex2html_wrap_inline34 as tex2html_wrap_inline36 where tex2html_wrap_inline38 denotes the ranking of event i in the correct chronological order and a sequence of student responses tex2html_wrap_inline42 where tex2html_wrap_inline44 denotes the chronological rank given by the student to event i; determine the length of the longest (not necessarily contiguous) sequence of events in the student responses that are in the correct chronological order relative to each other.

The Input

The first line of the input will consist of one integer n indicating the number of events with tex2html_wrap_inline50 . The second line will contain nintegers, indicating the correct chronological order of n events. The remaining lines will each consist of n integers with each line representing a student's chronological ordering of the n events. All lines will contain n numbers in the range tex2html_wrap_inline60 , with each number appearing exactly once per line, and with each number separated from other numbers on the same line by one or more spaces.

The Output

For each student ranking of events your program should print the score for that ranking. There should be one line of output for each student ranking.

Sample Input 1

4
4 2 3 1
1 3 2 4
3 2 1 4
2 3 4 1

Sample Output 1

1
2
3

Sample Input 2

10
3 1 2 4 9 5 10 6 8 7
1 2 3 4 5 6 7 8 9 10
4 7 2 3 10 6 9 1 5 8
3 1 2 4 9 5 10 6 8 7
2 10 1 3 8 4 9 5 7 6

Sample Output 2

6
5
10
9



Source Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * The notes from algorithmist is very important;
 * Plus, the essential part of this problem is very easy, just Longest Common
 * Subsequence.
 */

/**
 * @author antonio081014
 * @since Jan 28, 2012, 7:42:17 PM
 */
class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        String[] inorder = br.readLine().split(" ");
        inorder = reorder(inorder);
        String strLine;
        while ((strLine = br.readLine()) != null) {
            String[] outorder = strLine.split(" ");
            outorder = reorder(outorder);
            System.out.println(LCS(inorder, outorder, N));
        }
    }

    public static String[] reorder(String[] list) {
        String[] ret = new String[list.length];
        for (int i = 0; i < list.length; i++) {
            ret[Integer.parseInt(list[i]) - 1] = Integer.toString(i + 1);
        }
        return ret;
    }

    public static int LCS(String[] a, String[] b, int N) {
        int cnt = 0;
        int[][] dp = new int[N + 1][N + 1];
        // int[][] count = new int[N + 1][N + 1];
        for (int i = 1; i <= N; i++) {
            if (a[i - 1].compareTo(b[i - 1]) == 0)
                cnt++;
            for (int j = 1; j <= N; j++) {
                if (a[i - 1].compareTo(b[j - 1]) == 0) {
                    // if (dp[i][j] * count[i][j] < (1 + dp[i - 1][j - 1])
                    // * count[i - 1][j - 1]) {
                    // dp[i][j] = 1 + dp[i - 1][j - 1];
                    // count[i][j] = count[i - 1][j - 1];
                    // }
                    // else if (dp[i][j] * count[i][j] == (1 + dp[i - 1][j - 1])
                    // * count[i - 1][j - 1]) {
                    // count[i][j]++;
                    // }
                    dp[i][j] = Math.max(dp[i][j], 1 + dp[i - 1][j - 1]);
                }
                else {
                    // if (dp[i][j] * count[i][j] < (dp[i - 1][j])
                    // * count[i - 1][j]) {
                    // dp[i][j] = dp[i - 1][j];
                    // count[i][j] = count[i - 1][j];
                    // }
                    // if (dp[i][j] * count[i][j] < (dp[i][j - 1])
                    // * count[i][j - 1]) {
                    // dp[i][j] = dp[i][j - 1];
                    // count[i][j] = count[i][j - 1];
                    // }
                    dp[i][j] = Math.max(dp[i][j],
                            Math.max(dp[i - 1][j], dp[i][j - 1]));
                }
            }
        }
        return dp[N][N];
    }
}

Tuesday, January 24, 2012

UVa_00103_Stacking_Boxes.java

Problem Links:

uva00103,

Problem:


 Stacking Boxes 

Background

Some concepts in Mathematics and Computer Science are simple in one or two dimensions but become more complex when extended to arbitrary dimensions. Consider solving differential equations in several dimensions and analyzing the topology of an n-dimensional hypercube. The former is much more complicated than its one dimensional relative while the latter bears a remarkable resemblance to its ``lower-class'' cousin.

The Problem

Consider an n-dimensional ``box'' given by its dimensions. In two dimensions the box (2,3) might represent a box with length 2 units and width 3 units. In three dimensions the box (4,8,9) can represent a box tex2html_wrap_inline40 (length, width, and height). In 6 dimensions it is, perhaps, unclear what the box (4,5,6,7,8,9) represents; but we can analyze properties of the box such as the sum of its dimensions.
In this problem you will analyze a property of a group of n-dimensional boxes. You are to determine the longest nesting string of boxes, that is a sequence of boxes tex2html_wrap_inline44 such that each box tex2html_wrap_inline46 nests in box tex2html_wrap_inline48 ( tex2html_wrap_inline50 .
A box D = ( tex2html_wrap_inline52 ) nests in a box E = ( tex2html_wrap_inline54 ) if there is some rearrangement of the tex2html_wrap_inline56 such that when rearranged each dimension is less than the corresponding dimension in box E. This loosely corresponds to turning box D to see if it will fit in box E. However, since any rearrangement suffices, box D can be contorted, not just turned (see examples below).
For example, the box D = (2,6) nests in the box E = (7,3) since D can be rearranged as (6,2) so that each dimension is less than the corresponding dimension in E. The box D = (9,5,7,3) does NOT nest in the box E = (2,10,6,8) since no rearrangement of D results in a box that satisfies the nesting property, but F = (9,5,7,1) does nest in box E since F can be rearranged as (1,9,5,7) which nests in E.
Formally, we define nesting as follows: box D = ( tex2html_wrap_inline52 ) nests in box E = ( tex2html_wrap_inline54 ) if there is a permutation tex2html_wrap_inline62 oftex2html_wrap_inline64 such that ( tex2html_wrap_inline66 ) ``fits'' in ( tex2html_wrap_inline54 ) i.e., if tex2html_wrap_inline70 for all tex2html_wrap_inline72 .

The Input

The input consists of a series of box sequences. Each box sequence begins with a line consisting of the the number of boxes k in the sequence followed by the dimensionality of the boxes, n (on the same line.)
This line is followed by k lines, one line per box with the n measurements of each box on one line separated by one or more spaces. Thetex2html_wrap_inline82 line in the sequence ( tex2html_wrap_inline84 ) gives the measurements for the tex2html_wrap_inline82 box.
There may be several box sequences in the input file. Your program should process all of them and determine, for each sequence, which of the k boxes determine the longest nesting string and the length of that nesting string (the number of boxes in the string).
In this problem the maximum dimensionality is 10 and the minimum dimensionality is 1. The maximum number of boxes in a sequence is 30.

The Output

For each box sequence in the input file, output the length of the longest nesting string on one line followed on the next line by a list of the boxes that comprise this string in order. The ``smallest'' or ``innermost'' box of the nesting string should be listed first, the next box (if there is one) should be listed second, etc.
The boxes should be numbered according to the order in which they appeared in the input file (first box is box 1, etc.).
If there is more than one longest nesting string then any one of them can be output.

Sample Input

5 2
3 7
8 10
5 2
9 11
21 18
8 6
5 2 20 1 30 10
23 15 7 9 11 3
40 50 34 24 14 4
9 10 11 12 13 14
31 4 18 8 27 17
44 32 13 19 41 19
1 2 3 4 5 6
80 37 47 18 21 9

Sample Output

5
3 1 2 4 5
4
7 2 5 6



Source Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Essentially, it's a Longest-Increasing-Subsequence problem, so we could solve
 * it with Dynamic Programming.
 *
 * 1st, sort the dimensions for each box;(This permutation could be compared
 * more easily, since any permutation is essentially the same.)
 * 2nd, sort the boxes, any two boxes could be compared dim by dim,
 * 3rd, use dynamic programming to solve the problem, list[i].best is the
 * maximum number, while use parent to keep the track.
 * 4th, use the track to backtrack the list of boxes's id;
 *
 */

/**
 * @author antonio081014
 * @since Jan 24, 2012, 5:29:40 PM
 */
class Main {

    public static List<Box> list;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String strLine;
        while ((strLine = br.readLine()) != null) {
            String[] strs = strLine.split(" ");
            int k = Integer.parseInt(strs[0]);
            int n = Integer.parseInt(strs[1]);
            list = new ArrayList<Box>();
            for (int i = 0; i < k; i++) {
                strs = br.readLine().split(" ");
                list.add(new Box(i, n, strs));
            }
            Collections.sort(list);

            int[] parent = new int[k];
            for (int i = 0; i < k; i++)
                parent[i] = i;
            int best = -1;
            int index = -1;
            for (int i = 0; i < k; i++) {
                for (int j = 0; j < i; j++) {
                    if (list.get(i).compare(list.get(j))
                            && list.get(i).best < list.get(j).best + 1) {
                        list.get(i).best = list.get(j).best + 1;
                        parent[i] = j;
                    }
                }
                if (list.get(i).best > best) {
                    best = list.get(i).best;
                    index = i;
                }
            }
            // for (int i = 0; i < k; i++) {
            // System.out.println(list.get(i).id + " " + parent[i] + " "
            // + list.get(i).best);
            // }

            System.out.println(best);
            List<Integer> nums = new ArrayList<Integer>();

            while (index != parent[index]) {
                nums.add(list.get(index).id + 1);
                index = parent[index];
            }
            nums.add(list.get(index).id + 1);
            String output = "";
            for (int i = nums.size() - 1; i >= 0; i--) {
                output += Integer.toString(nums.get(i)) + " ";
            }
            System.out.println(output.substring(0, output.length() - 1));
        }
    }
}

class Box implements Comparable<Box> {
    public int[] dims;
    public int   id;
    public int   best;

    public Box(int id, int n, String[] strs) {
        this.best = 1;
        this.id = id;

        dims = new int[n];
        for (int i = 0; i < n; i++)
            dims[i] = Integer.parseInt(strs[i]);
        Arrays.sort(dims);
    }

    public boolean compare(Box a) {
        for (int i = 0; i < this.dims.length; i++) {
            if (this.dims[i] <= a.dims[i])
                return false;
        }
        return true;
    }

    @Override
    public int compareTo(Box arg0) {
        for (int i = 0; i < dims.length; i++) {
            if (this.dims[i] < arg0.dims[i])
                return -1;
            else if (this.dims[i] > arg0.dims[i])
                return 1;
        }
        return 0;
    }

    @Override
    public String toString() {
        String ret = "";
        for (int i = 0; i < dims.length; i++)
            ret += dims[i] + " ";
        return ret;
    }
}

Thursday, January 19, 2012

SRM530

Level 1 Level 2 Level 3
Div 1 Level 1 Level 2 Level 3
Div 2 Level 1 Level 2 Level 3

Tutorials:

SRM530


Division One - Level Three:

Solution

Source Code:


Division One - Level Two:

Solution

Source Code:


Division One - Level One:

Solution

The same with Div2-Lev2.

Source Code:


Sivision Two - Level Three:

Solution

Source Code:


Division Two - Level Two:

Solution

Brute-force. Even here I made a minor mistake, which assume the cutter will start with a dot, what a joke.

Source Code:

/**
 * @author antonio081014
 * @since Jan 19, 2012, 6:25:15 PM
 */

public class GogoXCake {
    public String solve(String[] cake, String[] cutter) {
        for (int i = 0; i + cutter.length <= cake.length; i++) {
            for (int j = 0; j + cutter[0].length() <= cake[i].length(); j++) {
                if (checkCutter(cake, cutter, i, j)) {
                    for (int x = 0; x < cutter.length; x++) {
                        for (int y = 0; y < cutter[x].length(); y++) {
                            if (cutter[x].charAt(y) == '.')
                                cake[i + x] = cake[i + x].substring(0, y + j)
                                        + "X"
                                        + cake[i + x].substring(y + j + 1);
                        }
                    }
                }
            }
        }
        return checkCake(cake) ? "YES" : "NO";
    }

    public void print(String[] cake) {
        for (int i = 0; i < cake.length; i++)
            System.out.println(cake[i]);
    }

    public boolean checkCake(String[] cake) {
        for (int i = 0; i < cake.length; i++)
            for (int j = 0; j < cake[i].length(); j++)
                if (cake[i].charAt(j) == '.')
                    return false;
        return true;
    }

    public boolean checkCutter(String[] cake, String[] cutter, int x, int y) {
        for (int i = 0; i < cutter.length; i++) {
            for (int j = 0; j < cutter[i].length(); j++) {
                if (cutter[i].charAt(j) == '.')
                    if (cake[i + x].charAt(j + y) != cutter[i].charAt(j)) {
                        return false;
                    }
            }
        }
        return true;
    }

    // <%:testing-code%>
}
// Powered by [KawigiEdit] 2.0!


Division Two - Level One:

Solution

I used the brute-force, which go through all the permutations.

Source Code:

//Thursday, January 19, 2012 17:51 PST
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

class GogoXBallsAndBinsEasy {
public:
  int solve(vector <int>);
};

int GogoXBallsAndBinsEasy::solve(vector <int> T) {
  vector<int> v(T.begin(), T.end());
  sort(v.begin(), v.end());
  sort(T.begin(), T.end());
  int count = 0;
  do{
    int tmp = 0;
    for(int i=0; i<v.size(); i++){
      tmp += (v[i] - T[i]) >0? (v[i]-T[i]) : 0;
    }
    count = max(count, tmp>0? tmp:-tmp);
  }while(next_permutation(v.begin(), v.end()));
  return count;
}


//Powered by [KawigiEdit] 2.0!

Sunday, January 15, 2012

Insertion Sort @ InterviewStreet

Problem Links:

Interviewstreet,

Problem:


Insertion Sort (25 Points)
Insertion Sort is a classical sorting technique. One variant of insertion sort works as follows when sorting an array a[1..N] in non-descending order:
for i  = 2 to N    j = i   while j > 1 and a[j] < a[j - 1]        swap a[j] and a[j - 1]
        j = j-1 
The pseudocode is simple to follow. In the ith step, element a[i] is inserted in the sorted sequence a[1..i - 1]. This is done by moving a[i] backward by swapping it with the previous element until it ends up in it's right position.
As you probably already know, the algorithm can be really slow. To study this more, you want to find out the number of times the swap operation is performed when sorting an array.
Input:
The first line contains the number of test cases T. T test cases follow. The first line for each case contains N, the number of elements to be sorted. The next line contains N integers a[1],a[2]...,a[N].
Output:
Output T lines, containing the required answer for each test case.
Constraints:
1 <= T <= 5
1 <= N <= 100000
1 <= a[i] <= 1000000
Sample Input:
2
5
1 1 1 2 2
5
2 1 3 1 2
Sample Output:
0


Source Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * This problem actually ask the coder to count the number of inversions.
 * The updated merge-sort could count this number perfectly.
 */

/**
 * @author antonio081014
 * @since Jan 8, 2012, 4:41:26 PM
 */
public class Solution {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // BufferedReader br = new BufferedReader(new InputStreamReader(
        // new DataInputStream(new FileInputStream("input.txt"))));
        // BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
        // "output.txt")));
        int T = Integer.parseInt(br.readLine());
        for (int t = 0; t < T; t++) {
            int N = Integer.parseInt(br.readLine());
            int[] nums = new int[N];
            String[] strs = br.readLine().split(" ");
            for (int j = 0; j < N; j++)
                nums[j] = Integer.parseInt(strs[j]);
            System.out.println(Long.toString(sort_and_count(nums, 0, N - 1)));
            // bw.write(Long.toString(sort_and_count(nums, 0, N - 1)) + "\n");
        }
        // br.close();
        // bw.close();
    }

    public static long sort_and_count(int[] a, int x1, int x2) {
        if (x2 <= x1)
            return 0L;
        if (x2 == x1 + 1) {
            if (a[x1] > a[x2]) {
                a[x1] ^= a[x2];
                a[x2] ^= a[x1];
                a[x1] ^= a[x2];
                return 1L;
            }
            return 0L;
        }
        int mid = (x2 + x1) / 2;
        long count = 0L;
        count += sort_and_count(a, x1, mid);
        count += sort_and_count(a, mid + 1, x2);
        count += merge_and_count(a, x1, mid, mid + 1, x2);
        return count;
    }

    public static long merge_and_count(int[] a, int x1, int x2, int y1, int y2) {
        long count = 0L;
        for (int i = x1, j = y1; i <= x2 && j <= y2;) {
            if (a[i] > a[j]) {
                count += (long) (x2 - i + 1);
                j++;
            }
            else
                i++;
        }
        Arrays.sort(a, x1, y2 + 1);
        return count;
    }

    public static long insertSort(int[] a) {
        long count = 0;
        for (int i = 1; i < a.length; i++) {
            int j = i;
            while (j >= 1 && a[j] < a[j - 1]) {
                a[j] ^= a[j - 1];
                a[j - 1] ^= a[j];
                a[j] ^= a[j - 1];
                count++;
                j--;
            }
        }
        return count;
    }
}