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 to the only line of output. Sample input:
bcd Sample output:
题目:如果一个字符串全部由小写字母组成,并且所有相邻字母都不同,那么这种字符串称为sstring。给定一个字符串,请统计与此字符串长度相同,且字典序不大于该字符串的所有sstring的个数。由于结果可能很大,所以结果对1009取余。
解法:这是典型的数位动态规划题目了。由于相邻字母不能相同,那么dp[i] = dp[i - 1] * (26 - 1)。对于给定的字符串,逐位进行统计和累加即可。要注意给定的字符串有可能不是sstring,也可能是,所以得加以检查。
代码:
// http://www.careercup.com/question?id=23869663
#include <iostream>
#include <string>
#include <vector>
using namespace std; int countSString(const string &s, const int mod)
{
vector<int> v;
int i, n; n = (int)s.length();
v.resize(n);
v[] = % mod;
for (i = ; i < n; ++i) {
v[i] = v[i - ] * % mod;
} int count = ;
char prev = 'z' + ;
for (i = ; i < n; ++i) {
if (prev >= s[i]) {
count = (count + (s[i] - 'a') * v[n - - i]) % mod;
} else {
count = (count + (s[i] - 'a' - ) * v[n - - i]) % mod;
}
if (prev == s[i]) {
break;
} else {
prev = s[i];
}
} v.clear();
return i == n ? count + : count;
} int main()
{
string s;
const int mod = ; while (cin >> s) {
cout << countSString(s, mod) << endl;
} return ;
}