F - Beauty of Array

本文介绍了一种高效算法,用于解决求序列所有子序列的Beauty和的问题。Beauty定义为序列中不同整数之和。算法通过跟踪每个数字首次出现的位置来优化计算过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

F - Beauty of Array

https://vjudge.net/contest/225989#problem/F

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和

  1 <= N <= 100000


解题思路】由于数据比较大,常规方法求字序列和肯定是行不通的,我们不妨这样想:因为要区别于不同的数

,可以看成序列里的数是一个一个加进去的,每次加入一个数,统计前面序列里第一次出现新加入的这个数的位置,表达的不好,

举个例子:

1 2 3

定义dp(当前元素前面(包括自己)所有包含自己的字序列的和)

定义sum(当前元素前面所有字序列的和,包括此元素)

//输入   1     2     3

//c      1     5     14

//sum   1     6      20

//a[i]      1     2      3


   AC代码:

# include <stdio.h>
# include <string.h>

int a[100001];

int main(void)
{
	int t, b, i, e;
	long long sum, c;
	scanf("%d", &t);
	while (t --)
	{
		memset(a, 0, sizeof(a));
		scanf("%d", &b);
		sum = 0, c = 0;
		for (i = 1; i <= b; i ++)
		{
			scanf("%d", &e);
			c += (i - a[e])*e;
			sum += c;
			a[e] = i;
		}
		printf("%lld\n", sum);
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值