首页 技术 正文
技术 2022年11月14日
0 收藏 700 点赞 4,162 浏览 1389 个字

http://www.51nod.com/onlineJudge/questionCode.html

这题看起来挺复杂,但是真正的dp还是挺好理解的。唯独是想不到的,应该把样例模拟一遍。

比如1、2、4、2

考虑第一个,只有“1”这一个子序列

考虑前两个,有:“1”, “12”, “2”

前三个,有:“1”, “12”, “2”, “14”,“124”,“24”,“4”

可以发现,dp[i]是可以从dp[i – 1]推过来的,第一,打破dp[i – 1]的合法情况要保留,第二,可以加入字符a[i]和前i – 1个组成的不重复的情况结合,得到新的结果,第三,a[i]自己单独做一个。

所以如果不考虑重复,那么dp[i] = 2 * dp[i – 1] + 1

但是考虑前4个,则会出现重复的情况。

首先,dp[3]的应该全部照写下来。“1”, “12”, “2”, “14”,“124”,“24”,“4”

然后,用a[4]去结合 的话。会有,”12″(重复), “122”, “22”, “142”, “1242”, “242”, “42”, “2”(重复)

那么需要减去重复的部分,减去多少呢?

观察到,最近出现相同数字(那个数字2)的位置是2,而且dp[2] =3,哪么,就是用a[2]生成dp[2]的时候的合法情况和现在的重复了,因为用a[2]生成dp[2]的时候,也就是从dp[1]递推过来,我们也保存了dp[1]的合法情况,那么既然用dp[1] + a[2]生成了某些情况,那么当a[4] == a[2]的时候,就没必要再用dp[1]那些合法情况来生成dp[4],因为已经保存在dp[2]中了。所以这个需要减去。

所以需要不断hash到最右的位置。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <assert.h>
#define IOS ios::sync_with_stdio(false)
using namespace std;
#define inf (0x3f3f3f3f)
typedef long long int LL;#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <bitset>
const int MOD = 1e9 + ;
int a[ + ];
int tohash[ + ];
long long int dp[ + ];
void work () {
int n;
cin >> n;
for (int i = ; i <= n; ++i) {
cin >> a[i];
}
dp[] = ;
tohash[a[]] = ;
for (int i = ; i <= n; ++i) {
if (tohash[a[i]]) {
dp[i] = (dp[i - ] * + - (dp[tohash[a[i]] - ] + ) + MOD) % MOD;
} else {
dp[i] = (dp[i - ] * + ) % MOD;
}
tohash[a[i]] = i;
}
printf("%d\n", dp[n]);
}
int main () {
#ifdef local
freopen("data.txt", "r", stdin);
// freopen("data.txt", "w", stdout);
#endif
work ();
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,111
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,203
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,838
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,922