DP(动态规划)学习笔记

代码实现是一个从小到大的过程,思维方式是正向思维。第一个子问题最优。第二子问题最优。第三个子问题最优。。。。
整个问题最优。
思考是一个从大到小的过程。要整个问题最优,那么它的子问题最优,依次找它的子问题,直到找到易解决的最优子问题。
代码分析的是问题的中间过程,也是最难的的,要向前向后看,考虑可能遇到的所有情况,在各种情况下让其达到最优。

题目描述
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值