ZOJ - 3872 —— Beauty of Array —— dp

本文介绍了一种计算数组所有子序列中不重复元素之和的方法,并通过具体示例详细解释了算法实现过程。

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


题意:先定义一个最美数组的概念,就是说一个连续的数组中,不重复的数字的加和。

然后这道题是给你一个长度为n的数组,让你求这个数组的所有子最美数组的加和。

用一个cur数组标记当前元素上一次出现时的坐标是多少。这样一来递推公式如下:

dp[i] = dp[i-1] + (i-cur[p[i]])*p[i];

比如说 

4

2 3 1 3

这个样例吧。

i = 1      dp[i] = 2;   {2}

i = 2      dp[i] = dp[i-1]+(i-cur[p[i]])*p[i];    {23} , {3}

i = 3      dp[i] = dp[i-1]+(i-cur[p[i]])*p[i];    {123} , {3,1} , {1}

i = 4      dp[i] = dp[i-1]+(i-cur[p[i]])*p[i];    {123} , {3,1} , {13} , {3}

正因为最美数组的定义,子数组中的相同元素+一遍就OK了。所以记录第一次出现的坐标。


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;

#define MAX_N 100005
#define INF 0x3f3f3f3f
#define Mem(a,x) memset(a,x,sizeof(a))
#define ll long long
ll dp[MAX_N];
int p[MAX_N],cur[MAX_N*10];
int main()
{
    int n;
    cin>>n;
    while(n--) {
        int m;
        cin>>m;
        Mem(dp,0);
        Mem(cur,0);
        for(int i = 1; i<=m; i++) {
            cin>>p[i];
        }
        for(int i = 1; i<=m; i++) {
            //cout<<i<<' '<<cur[p[i]]<<endl;
            dp[i] = dp[i-1] + (i-cur[p[i]])*p[i];
            cur[p[i]] = i;
        }
        ll ans = 0;
        for(int i = 1; i<=m; i++) {
            ans += dp[i];
           // cout<<dp[i]<<endl;;
        }
        printf("%lld\n",ans);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值