• Careercup


    2014-05-02 03:37

    题目链接

    原题:

    A string is called sstring if it consists of lowercase english letters and no two of its consecutive characters are the same. 
    
    You are given string s of length n. Calculate the number of sstrings of length that are not lexicographically greater than s. 
    Input format 
    The only line of input contains the string s. It's length is not greater than 100. 
    All characters of input are lowercase english letters. 
    
    Output format: 
    Print the answer of test modulo 1009 to the only line of output. 
    
    Sample input: 
    bcd 
    
    Sample output: 
    653

    题目:如果一个字符串全部由小写字母组成,并且所有相邻字母都不同,那么这种字符串称为sstring。给定一个字符串,请统计与此字符串长度相同,且字典序不大于该字符串的所有sstring的个数。由于结果可能很大,所以结果对1009取余。

    解法:这是典型的数位动态规划题目了。由于相邻字母不能相同,那么dp[i] = dp[i - 1] * (26 - 1)。对于给定的字符串,逐位进行统计和累加即可。要注意给定的字符串有可能不是sstring,也可能是,所以得加以检查。

    代码:

     1 // http://www.careercup.com/question?id=23869663
     2 #include <iostream>
     3 #include <string>
     4 #include <vector>
     5 using namespace std;
     6 
     7 int countSString(const string &s, const int mod)
     8 {
     9     vector<int> v;
    10     int i, n;
    11     
    12     n = (int)s.length();
    13     v.resize(n);
    14     v[0] = 1 % mod;
    15     for (i = 1; i < n; ++i) {
    16         v[i] = v[i - 1] * 25 % mod;
    17     }
    18     
    19     int count = 0;
    20     char prev = 'z' + 1;
    21     for (i = 0; i < n; ++i) {
    22         if (prev >= s[i]) {
    23             count = (count + (s[i] - 'a') * v[n - 1 - i]) % mod;
    24         } else {
    25             count = (count + (s[i] - 'a' - 1) * v[n - 1 - i]) % mod;
    26         }
    27         if (prev == s[i]) {
    28             break;
    29         } else {
    30             prev = s[i];
    31         }
    32     }
    33 
    34     v.clear();
    35     return i == n ? count + 1 : count;
    36 }
    37 
    38 int main()
    39 {
    40     string s;
    41     const int mod = 1009;
    42     
    43     while (cin >> s) {
    44         cout << countSString(s, mod) << endl;
    45     }
    46     
    47     return 0;
    48 }
  • 相关阅读:
    域名申请攻略(以godaddy+支付宝为例)
    初始java白盒测试junit的使用
    微型oracle学习使用—oracle XE(oracle express edition
    VBS学习创建桌面快捷方式
    强烈推荐Oracle的入门心得
    Godaddy域名注册详细图文教程(转)
    如何用WordPress搭建自己的博客(转)
    图解eclipse+myeclipse完全绿色版制作过程
    java整理的经典的bug问题白盒问题(转)
    eclipse插件整理集合(包括myeclipse插件)转
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3703632.html
Copyright © 2020-2023  润新知