思维 ZOJ 3872 Beauty of Array

探讨了一种算法,用于求解数组中所有连续子数组的不同整数之和,通过跟踪每个数字最后出现的位置来高效解决该问题。

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

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.

<h4< dd="">Output

For each case, print the answer in one line.

<h4< dd="">Sample Input
3
5
1 2 3 4 5
3
2 3 3
4
2 3 3 2
<h4< dd="">Sample Output
105
21
38


          这是一道思维题,很烧脑,让求数组中连续子集的不同数字的和;
          2   3   3
          2                =2
          3                =3
          3                =3
          2  3            =5
          3  3            =3
          2 3 3          =5
          总和就为 2+3+3+5+3+5=21

此种类型的题首先要知道一定是有规律可循的
例如,1  2  3  4  5   这个数组的总和可以看作是  1  2  3  4 的总和再加上由5产生的新子集合的和
即:
1  2  3  4  5 
    2  3  4  5
        3  4  5
            4  5
                5
那么由5产生的新的子集合的总值是多少呢?
可以观察出  由4产生的新子集的值 再加上5的个数就行了
即:p + 5 * 5  (p为上一个新增元素产生的新增连续子集的总值)
那么如果新增子集与前面的元素重复怎么办呢?
例:1  2  3  4  的新增元素为 3;
即:
1  2  3  4  3
    2  3  4  3
        3  4  3
            4  3
                3
因为与前面的3个子集里面的数字3有重复,后面两组没有重复的数字3
即   p+3*2,
为什么是3*2呢?2怎么来的?
可以知道当前的 3 的位置减去前面的 3 的位置为2;
就是说如果新增元素与之前某个元素重合,那么由新增元素产生的新增子序列的总值就为 p+x*i (x为新增元素,i为当前元素位置和上一个相同元素的差)
如果有多个重复的怎么办呢?
例:1   3  2  3  4 的新增元素为 3
1  3  2  3  4  3
    3  2  3  4  3
        2  3  4  3
            3  4  3
                4  3
                    3
很明显,只要找出 3 和上一个最近 3 的距离即可;

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
long long s1[1000005],w[1000005];
int main()
{
	long long n,a,b,c;
	cin>>a;
	while(a--){
	cin>>n;
	memset(w,0,sizeof(w));
	long long sum=0,p=0;
	for(int i=1;i<=n;i++)
	{
		cin>>s1[i];
		p=p+s1[i]*(i-w[s1[i]]);//第二个p是上一个新增元素产生的新增连续子集的总值; 第一个p为当前新增元素产生的新增连续子集的值 
		sum+=p;
		w[s1[i]]=i;//此处用到了桶排序,记录当前元素最后一次出现的位置 
	} 
	cout<<sum<<endl;
  }
} 




 

     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值