ZOJ-3872Beauty 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.

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个数,你求这n个数的子序列中不算重复的数的和,比如第二个样例他的子序列就是{2},{2,3},{2,3,3},{3},{3,3},{3};但每个子序列中重复的元素不被算入,所以他们的总和就是2+5+5+3+3+3=21;

思路:这个题如果暴力的话肯定是会超时的,因为有大量重复的计算,而设计算法的目的就是避免这些重复的计算,我们可以牺牲空间,把这些需要多次使用的数值存起来。所以我的思路是采用动态规划的思路,虽然比赛时也想到了动态规划,但却在处理重复元素时怎么也想不出来了,我们还是太弱了。。。

更加具体的解释在代码的注释里面,完整代码如下:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAX 100010
using namespace std;
int book[MAX*10],num[MAX];//用book标记这个元素最后出现的位置 
long long int dp[MAX]; 
/*对于2 3 3 2这个样例,我们从后往前来看,一个2他能构成的子序列只有1个即{2},故dp[1]=2;然后对于第二个3他能
构成{3},{3,2},即相当于这个数的能构成的子序列数乘上这个数,故dp[2]=1*num[1]+dp[1],但我们如何来判定重复元素呢,
就是我们用一个数组来记录一下这个元素最后出现在那个位置,故我们对于第i个数的公式就是dp[i] = (i-book[num[i]])*num[i] + dp[i-1]*/ 
int main(void){
    int t,n;
    scanf("%d",&t);
    while(t--){
        memset(book,0,sizeof(book));
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            scanf("%d",&num[i]);
        reverse(num+1,num+1+n);
        for(int i=1;i<=n;i++){
            dp[i] = (i-book[num[i]])*num[i] + dp[i-1];
            book[num[i]] = i;
        }
        long long int sum = 0;
        for(int i=1;i<=n;i++)//对于每个数能组成的序列和加在一起就是结果了 
            sum += dp[i];
        printf("%lld\n",sum);
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值