思维 ZOJ 3872 Beauty of Array

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;
  }
} 


 
  

 

扫描二维码关注公众号,回复: 188246 查看本文章

     

猜你喜欢

转载自blog.csdn.net/guozuofeng/article/details/80144590