Count Tuples

4.4

5 votes
Segment tree, Advanced Data Structures, Data Structures, Fenwick (Binary Indexed) Trees
Problem

You are given an array A having N integers. Find the number of triplets (i,j,k) such that 

  • 1i<j<kN.
  • The integer Aj is equal to the median of the integers Ai,Aj,Ak.

The median of three integers is the middle element after sorting the three integers. For example, the median of (5,1,3) is 3(2,4,4) is 4.

Input format

  • The first line of input contains an integer T denoting the number of test cases. The description of each test case is as follows:
  • The first line of each test case contains an integers N.
  • The second line of each test case contains N integers A1,A2,,AN.

Output format

For each test case, print the number of triplets that satisfies the given conditions in a separate line.

Constraints

1T1051N1051AiNSum of N over all test cases does not exceed 3105.

 

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

In the first test case, there are 2 tuples that satisfy the given conditions:

  • (1,2,4): The median of (A1,A2,A4)=(3,5,5) is 5 which is equal to A2.
  • (2,4,5): The median of (A2,A4,A5)=(5,5,4) is 5 which is equal to A4.

Editor Image

?