代码实现是一个从小到大的过程,思维方式是正向思维。第一个子问题最优。第二子问题最优。第三个子问题最优。。。。
整个问题最优。
思考是一个从大到小的过程。要整个问题最优,那么它的子问题最优,依次找它的子问题,直到找到易解决的最优子问题。
代码分析的是问题的中间过程,也是最难的的,要向前向后看,考虑可能遇到的所有情况,在各种情况下让其达到最优。
题目描述
There are N stones arranged in a row. The i-th stone from the left is painted in the color Ci.
Snuke will perform the following operation zero or more times:
Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.
Find the number of possible final sequences of colors of the stones, modulo 109+7.
Constraints
·1≤N≤2×105
·1≤Ci≤2×105(1≤i≤N)
·All values in input are integers.
输入
Input is given from Standard Input in the following format:
N
C1
:
CN
输出
Print the number of possible final sequences of colors of the stones, modulo 109+7.
样例输入
5
1
2
1
2
2
样例输出
3
提示
We can make three sequences of colors of stones, as follows:
·(1,2,1,2,2), by doing nothing.
·(1,1,1,2,2), by choosing the first and third stones to perform the operation.
·(1,2,2,2,2), by choosing the second and fourth stones to perform the operation
AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
const long long mod=1e9+7;
int n,a[maxn],b[maxn],c[maxn];
long long ans=1;
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]==a[i-1])
{
c[i]=c[i-1];
continue;
}
ans=(ans+c[b[a[i]]])%mod;
c[i]=ans;
b[a[i]]=i;
}
cout<<ans<<endl;
return 0;
}