hdu-5496 Beauty of Sequence(递推) Beauty of Sequence
题目链接:
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 813 Accepted Submission(s): 379
Problem Description
Sequence is beautiful and the beauty of an integer sequence is defined as follows: removes all but the first element from every consecutive group of equivalent elements of the sequence (i.e. unique function in C++ STL) and the summation of rest integers is the beauty of the sequence.
Now you are given a sequence }.
Now you are given a sequence }.
Input
There are multiple test cases. The first line of input contains an integer 2000000.
Output
For each test case, print the answer modulo 7 in a single line.
Sample Input
3
5
1 2 3 4 5
4
1 2 1 3
5
3 3 2 1 2
Sample Output
240
54
144
题意:
一个数列的美丽值为这个数列合并相邻的且相同的数后这个序列的和,现在给一个序列,求所有子序列的美丽值得和;
思路:
套路题,dp[i]表示以第i个为结尾的所有的序列的美丽值得和,那么就可以递推了
if a[j]==a[i],dp[i]+=dp[j];
else dp[i]+=dp[j]+num[j]*a[i];其中j属于[1,i-1],num[j]表示以j结尾的序列的个数;
这样会超时啊,用前缀和优化,然后开个map记录每个值结尾的序列的个数;
AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=1e5+10;
const LL mod=1e9+7;
LL dp[maxn],num,sum[maxn];
map<int,LL>mp;
int n,a[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
mp.clear();
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
sum[1]=a[1];num=1;mp[a[1]]=1;
for(int i=2;i<=n;i++)
{
dp[i]=(a[i]+sum[i-1])%mod;
dp[i]=(dp[i]+(num-mp[a[i]]+mod)%mod*a[i])%mod;
mp[a[i]]=(mp[a[i]]+num+1)%mod;
num=(num*2+1)%mod;
sum[i]=(sum[i-1]+dp[i])%mod;
}
printf("%lld
",sum[n]);
}
return 0;
}