Beauty of Array(思维)

本文介绍了一种计算数组所有连续子序列中不重复元素之和的方法,并提供了一个C++实现示例。通过记录每个元素最后一次出现的位置,有效地解决了问题。

摘要生成于 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.

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

这道题就是~~所有的连续子序列中~~不重复的元素的和是多少

这个题是要自己推出来一个规律

假设四个元素分别是ABCD~~那么在只有第一个元素的时候所有子序列和是A;而在有两个元素的时候(AB)这样的话是A+AB+B,比原来多了AB和B的和~~以此类推~~这样在多了第k个元素的时候~总的序列和增加的就是(上一个序列和增加的+k*这个元素)~~;

 这样的话如果是各个子序列(中的不同元素的和)的和呢::我们假设B和D相等~~辣么在增加到D的时候~D的实际上增加的就只有(ABC  BC CD D)少了(2)个D的值~~那如果是A和D相等呢,那么增加的就是(ABC BCD CD D)少了(1)个D~~~所以不同元素和这个每次增加的数量和这个元素上一次出现的位置有关~~这样就好做了

#include<bits/stdc++.h>
using namespace std;
int last[100005];
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        memset(last,0,sizeof(last));
        int n;
        cin>>n;
        long long ans=0;
        long long k=0;
        for(int i=1;i<=n;i++)
        {
            int t;
            cin>>t;
            k+=(i-last[t])*t;
            ans+=k;
            last[t]=i;
        }
        cout<<ans<<endl;
    }
    return 0;
}

参考博客:https://blog.youkuaiyun.com/chenshibo17/article/details/79994452

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值