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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)