Contents
  1. 1. Input
  2. 2. Output
  3. 3. Sample Input
  4. 4. Sample Output
  5. 5. 题目大意:
  6. 6. 分析:
  7. 7. 观察一个示例:

Edward has an array A with N integers. He defines the beauty of an array as the summation of all distinct integers in the array. Now Edward wants to know the summation of the beauty of all contiguous subarray of the array A.

Input

There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:

The first line contains an integer N (1 <= N <= 100000), which indicates the size of the array. The next line contains N positive integers separated by spaces. Every integer is no larger than 1000000.

Output

For each case, print the answer in one line.

Sample Input

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

Sample Output

105
21
38

题目大意:

定义Beauty数是一个序列里所有不相同的数的和,求一个序列所有连续子序列的Beauty和
如果子序列中有相同的元素,则这个元素只算一次。

分析:

  • a[]数组记录元素最近一次出现的位置

  • 定义状态: dp[i]代表第i个元素前面,包括第i个的所有连续子序列的和

  • sum为序列中所有Beauty数的总和

  • 状态转移方程:

dp[i] = dp[i - 1] + i x - a[x] x;

观察一个示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1 2 3 4 3

- 不出现相同元素的情况:

状态1 状态2 状态3 状态4
{1}
{1}, {2},{1,2}
{1}, {2},{1,2}, {3},{2,3},{1,2,3}
{1}, {2},{1,2}, {3},{2,3},{1,2,3}, {4},{3,4},{2,3,4},{1,2,3,4}

观察得:输入第i个元素,相应的连续子序列就多出i个,而这多出现的i个连续子序列是
在前一个状态里每个连续子序列里加这个元素得到的,
所以多出的是: dp[i - 1] + i * x;

- 出现不同元素的情况:

状态5

{1}, {2},{1,2}, {3},{2,3},{1,2,3}, {4},{3,4},{2,3,4},{1,2,3,4},
{3},{4,3},{3,4,3},{2,3,4,3},{1,2,3,4,3}

要减去多出现的第i个元素,就要找到最近一次出现第i个元素的位置,因为从这个位置
往前的所有连续子序列都含有这第i个元素,例如:3最近出现在第3个位置上,则第3个
元素前面,包括第3个的所有连续子序列,且这些连续子序列中都有3
所以减去的是: a[x] * x
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;

int a[100010];
unsigned long long dp[100010];

int main()
{

int T, n, x;
scanf("%d", &T);
while(T--){
unsigned long long sum = 0;
memset(a, 0, sizeof(a));
dp[0] = 0;
scanf("%d", &n);
for(int i = 1; i <= n; i++){
scanf("%d", &x);
dp[i] = dp[i - 1] + i * x - a[x] * x;
a[x] = i;
sum += dp[i];
}
printf("%llu\n", sum);
}
return 0;
}
Contents
  1. 1. Input
  2. 2. Output
  3. 3. Sample Input
  4. 4. Sample Output
  5. 5. 题目大意:
  6. 6. 分析:
  7. 7. 观察一个示例: