zoukankan      html  css  js  c++  java
  • 51nod 1202 不同子序列个数(计数DP)

    基准时间限制:1 秒 空间限制:131072 KB 分值: 40 
     
     
    子序列的定义:对于一个序列a=a[1],a[2],......a[n]。则非空序列a'=a[p1],a[p2]......a[pm]为a的一个子序列,其中1<=p1<p2<.....<pm<=n。
    例如4,14,2,3和14,1,2,3都为4,13,14,1,2,3的子序列。对于给出序列a,有些子序列可能是相同的,这里只算做1个,请输出a的不同子序列的数量。由于答案比较大,输出Mod 10^9 + 7的结果即可。
     
    Input
    第1行:一个数N,表示序列的长度(1 <= N <= 100000)
    第2 - N + 1行:序列中的元素(1 <= a[i] <= 100000)
    Output
    输出a的不同子序列的数量Mod 10^9 + 7。
    Input示例
    4
    1
    2
    3
    2
    Output示例
    13

    思路:
    我们知道如果不存在重复的数,那么dp[i]=dp[i-1]*2(含空集的情况)。现在考虑出现了重复的数。比如当前要取的数为a[i],
    且a[i]最近一次在之前的j位置出现过了。那么有dp[i]=dp[i-1]*2-dp[j-1]。所以我们利用一个数组mark记录下a[i]出现的位置就好了,没有出现过为0。
    代码:
     1 #include<bits/stdc++.h>
     2 #define db double
     3 #include<vector>
     4 #define ll long long
     5 #define vec vector<ll>
     6 #define Mt  vector<vec>
     7 #define ci(x) scanf("%d",&x)
     8 #define cd(x) scanf("%lf",&x)
     9 #define cl(x) scanf("%lld",&x)
    10 #define pi(x) printf("%d
    ",x)
    11 #define pd(x) printf("%f
    ",x)
    12 #define pl(x) printf("%lld
    ",x)
    13 const int N = 2e5 + 5;
    14 const int mod = 1e9 + 7;
    15 const int MOD = 998244353;
    16 const db  eps = 1e-18;
    17 const db  PI = acos(-1.0);
    18 using namespace std;
    19 int a[N],id[N];
    20 ll f[N];
    21 int main()
    22 {
    23     int n;
    24     ci(n);
    25     for(int i=1;i<=n;i++) ci(a[i]);
    26     memset(f,0,sizeof(f));
    27     memset(id,0,sizeof(id));
    28     f[0]=1;
    29     for(int i=1;i<=n;i++){
    30         if(!id[a[i]]) f[i]=f[i-1]*2%mod;
    31         else f[i]=(f[i-1]*2%mod-f[id[a[i]]-1]+2*mod)%mod;
    32         id[a[i]]=i;
    33     }
    34     pl(f[n]-1);
    35     return 0;
    36 }



  • 相关阅读:
    【leetcode】1415. The k-th Lexicographical String of All Happy Strings of Length n
    【leetcode】1413. Minimum Value to Get Positive Step by Step Sum
    【leetcode】1410. HTML Entity Parser
    【leetcode】1409. Queries on a Permutation With Key
    1, 2, and 4 symbols per clock中数据排列
    RGB转换成YCbCr
    RAW转换成RGB
    ROM的一种写法
    IP之ALTIOBUF仿真
    IP之ALTDDIO_in仿真
  • 原文地址:https://www.cnblogs.com/mj-liylho/p/7771818.html
Copyright © 2011-2022 走看看