zoukankan      html  css  js  c++  java
  • Good Bye 2015 D. New Year and Ancient Prophecy

    New Year and Ancient Prophecy

    题意:

    • 给一个长度为n(1<= n <= 5000)的只含有数字的字符串,字符串首位不为’0’;
    • 将字符串分割成数值严格递增的子串;并且每一个子串不能以0开头;这样的分割方式有多少种?

    思路:

    • 分割,显然要将每种情况都探究到,DP的特点。其中需要优化的点有
      1. 怎么快速比较两个子串表示的数值的大小?
        LCP(longest common prefix)使用数组lcp(a,b)表示以a,b开头的子串前缀相同字符的长度;初始化要为-1,不能为0;
      2. 如何构造dp式子。dp一般是从容易求解(情况少的子结构开始求解,之后组成复杂的结构),那分割有两个元素是必须的,一个是分割的位置,一个是子串的长度;还有更重要的要知道与子结构的关系。。重点:因为长度有代表数值大小的含义,那么不妨认为是dp:以l为左边界长度大于等于len的分法数;
      3. 转移方程: dp[l][len] += dp[l+len][len] ? dp[l+len][len+1];
        ?表示s[l…l+len] 是否大于 s[l+len…l+len+len]; 答案就是dp[0][1]中;
    #include<bits/stdc++.h>
    using namespace std;
    #define rep(i,n) for(int i = 0;i < (n);i++)
    #define MS1(a) memset(a,-1,sizeof(a))
    const int mod = 1e9+7;
    const int MAXN = 5050;
    int lcp[MAXN][MAXN],n;
    int dp[MAXN][MAXN];
    char S[MAXN];
    int LCP(int a,int b)
    {
        if(a >= n || b >= n) return 0;
        int& ret = lcp[a][b];
        if(~ret) return ret;
        ret = 0;
        if(S[a] == S[b]){
            ret = LCP(a+1,b+1) + 1;
        }
        return ret;
    }
    int f(int l,int len)    //以l为左端,长度大于等于len的分法数;
    {
        if(S[l] == '0') return 0;
        if(l + len > n) return 0;
        if(l + len == n) return 1;
        int& ret = dp[l][len];
        if(~ret) return ret;
        ret = 0;
        ret = f(l,len+1);   // ** 先求解子结构;
        if(l+len < n){
            int a = LCP(l,l+len);
            ret += (a<len&&S[l+a]<S[l+len+a])?f(l+len,len):f(l+len,len+1);
            if(ret >= mod) ret -= mod;   // 相加mod用减法更快~
        }
        return ret;
    }
    int main()
    {
        MS1(dp);MS1(lcp);
        scanf("%d%s",&n,S);
        printf("%d",f(0,1));
    }
    View Code
     
  • 相关阅读:
    Centos6.5下本地yum源及局域网yum源配置
    计算机网络之应用层_part -3
    计算机网络之应用层_part -2
    计算机网络之应用层_part -1
    LeetCode-Minimum Path Sum[dp]
    LeetCode-Interleaving String[dp]
    LeetCode-Best Time to Buy and Sell Stock III[dp]
    LeetCode-Palindrome Partitioning II[dp]
    用hexo + github 快速搭建个人博客,由于刚搭建好,有点小激动,就分享下,不好的地方还请指出,谢谢
    搭建node.js 本地服务器
  • 原文地址:https://www.cnblogs.com/hxer/p/5185137.html
Copyright © 2011-2022 走看看