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 }