This page is still under construction.

Parts of this page are still being built. What you see may change.

Permutation Graph

Interview

Time limit5sMemory limit256 MB

Summary
Given two permutations of 1 to n drawn on two parallel lines, count the pairs of segments joining equal numbers that cross.
Level

Medium5 of 10

Topics
Divide and conquer, Sorting
Solved
No attempts yet

Problem

A graph GG is a set of vertices VV together with a set of edges EE, written G=(V,E)G = (V, E). Both sets are usually listed out, but some graphs fix a construction rule instead of listing the edges. A permutation graph is one of those.

Take two permutations of {1,2,…,n}\{1, 2, \dots, n\}. Draw two parallel lines. On the upper line place the numbers from left to right in the order of the first permutation, and on the lower line place them in the order of the second permutation. Then join every number on the upper line to the same number on the lower line with a segment. The pairs of segments that cross are the edges of the permutation graph, and the vertices are the numbers 11 through nn.

When the two permutations are (2,5,4,1,3)(2, 5, 4, 1, 3) and (1,5,3,2,4)(1, 5, 3, 2, 4), six pairs of segments cross, so the permutation graph is V={1,2,3,4,5}V = \{1, 2, 3, 4, 5\}, E={(1,2),(1,4),(1,5),(2,3),(2,5),(3,4)}E = \{(1,2), (1,4), (1,5), (2,3), (2,5), (3,4)\}.

Given two permutations of {1,2,…,n}\{1, 2, \dots, n\}, write a program that counts the edges of the permutation graph they build.

Input

The first line contains the number of test cases TT. Each test case takes three lines. The first line holds nn (1≤n≤100,000)(1 \le n \le 100{,}000), and the next two lines hold one permutation each. Both are permutations of {1,2,…,n}\{1, 2, \dots, n\} and their elements are separated by spaces.

Output

For each test case, print the number of edges of the permutation graph on its own line.

Examples1

  1. Example 1

    Input
    3
    5
    2 5 4 1 3
    1 5 3 2 4
    7
    5 6 7 1 2 3 4
    5 6 7 1 2 3 4
    7
    1 5 3 4 2 7 6
    7 1 5 3 4 2 6
    
    Expected output
    6
    0
    5