CF BUDDY
← Problems·

1990C · Mad MAD Sum

1500 · brute force, greedy, math

Problem: We define the MAD\operatorname{MAD} (Maximum Appearing Duplicate) in an array as the largest number that appears at least twice in the array. Specifically, if there is no number that appears at least twice, the MAD\operatorname{MAD} value is 00.

For example, MAD([1,2,1])=1\operatorname{MAD}([1, 2, 1]) = 1, MAD([2,2,3,3])=3\operatorname{MAD}([2, 2, 3, 3]) = 3, MAD([1,2,3,4])=0\operatorname{MAD}([1, 2, 3, 4]) = 0.

You are given an array aa of size nn. Initially, a variable sumsum is set to 00.

The following process will be executed in a sequential loop until all numbers in aa become 00:

  1. Set sum:=sum+i=1naisum := sum + \sum_{i=1}^{n} a_i;
  2. Let bb be an array of size nn. Set bi:= MAD([a1,a2,,ai])b_i :=\ \operatorname{MAD}([a_1, a_2, \ldots, a_i]) for all 1in1 \le i \le n, and then set ai:=bia_i := b_i for all 1in1 \le i \le n.

Find the value of sumsum after the process.

Input Format: The first line contains an integer tt (1t21041 \leq t \leq 2 \cdot 10^4) — the number of test cases.

For each test case:

  • The first line contains an integer nn (1n21051 \leq n \leq 2 \cdot 10^5) — the size of the array aa;
  • The second line contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n (1ain1 \leq a_i \leq n) — the elements of the array.

It is guaranteed that the sum of nn over all test cases will not exceed 21052 \cdot 10^5.

Output Format: For each test case, output the value of sumsum in a new line.

Note: In the first test case, a=[1]a=[1] initially.

In the first loop:

  1. Set sum:=sum+a1=0+1=1sum := sum + a_1 = 0+1=1;
  2. Set b1:= MAD([a1])= MAD([1])=0b_1 :=\ \operatorname{MAD}([a_1])=\ \operatorname{MAD}([1])=0, and then set a1:=b1a_1 := b_1.

After the first loop, a=[0]a=[0] and the process ends. The value of sumsum after the process is 11.

In the second test case, a=[2,2,3]a=[2,2,3] initially.

After the first loop, a=[0,2,2]a=[0,2,2] and sum=7sum=7.

After the second loop, a=[0,0,2]a=[0,0,2] and sum=11sum=11.

After the third loop, a=[0,0,0]a=[0,0,0] and sum=13sum=13. Then the process ends.

The value of sumsum after the process is 1313.

Sample Cases

Case 1

Input

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

Output

1
13
9
40

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback