传送门ZOJ 3872
Beauty of Array
Time Limit: 2 Seconds Memory Limit: 65536 KB
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
Author: LIN, Xi
Source: The 12th Zhejiang Provincial Collegiate Programming Contest
Time Limit Exceeded 版
暴力
#include "cstdio"
#include "cstring"
#include "iostream"
#include "map"
using namespace std;
#define N 100005
int ans[N];
map<int,int> m;
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
m.clear();
scanf("%d",&n);
for(int i=;i<n;i++)
{
scanf("%d",&ans[i]);
}
int sum=;
int temp;
for(int i=;i<n;i++)
{
m[ans[i]]++;
temp=ans[i];
sum+=temp;
for(int j=i+;j<n;j++)
{
if(m.find(ans[j])==m.end())
{
m[ans[j]]++;
temp+=ans[j];
}
sum+=temp;
}
m.clear();
}
printf("%d\n",sum);
}
}
AC版
分析:
找规律:
数列如 1 2 3
前1个数 1,和为1
前2个数 1,2,加入之后有新子序列 2 1,2 即子序列之和 较次态多加 2*2(一个为值,一个为个数)
前3个数 1,2,3 加入之后有新子序列 3 2,3 1,2,3 即子序列之和 较次态多加 3*3(一个为值,一个为个数)
数列如 2 3 3
前1个数 2,和为2
前2个数 2,3,加入之后有新子序列 3 2,3 即子序列之和 较次态多加 3*2(一个为值,一个为个数)
前3个数 2,3,3 加入之后有新子序列 3 3,3 2,3,3 !!! 即子序列之和 较次态多加 3*(新加3的位置-前面出现3的最大位置),因为前面最后一个三之前的所有组合 再跟此时3组合,与新加数重复,不再加
2
3
2 3
3
3 3
2 3 3
得21
这样次态与现态的递推关系,就是DP问题了
而得出这种递推关系,就需要发掘规律
发掘规律,需要良好的数学思维
#include <cstdio>
#include <cstring>
#include "iostream"
using namespace std;
#define LL long long
int main()
{
int t,n;
int w[];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int x;
LL dp=,sum=;
memset(w,,sizeof(w));
for(int i=;i<=n;i++)
{
scanf("%d",&x);
dp+=(i-w[x])*x;
sum+=dp;
w[x]=i;
}
printf("%lld\n",sum);
}
}