微软2017校招笔试题2 composition
2016-10-12 19:57
281 查看
题目
Alice writes an English composition with a length of N characters. However, her teacher requires that M illegal pairs of characters cannot be adjacent, and if 'ab' cannot be adjacent, 'ba' cannot be adjacent either.In order to meet the requirements, Alice needs to delete some characters.
Please work out the minimum number of characters that need to be deleted.
给定一个由小写字母组成的字符串,规定某些字符不能相邻。求最少需要删除多少个字符使得剩下的字符串中不存在那些规定不能相邻的字符相邻。
解法
字符串中的字符只有26种可能,去除某些字符剩余的字符串只能以a-z这些字符结尾,如果记录 dp[c]表示以 字符 c+'a' 结尾的字符串的最长长度,则可以有递推公式dp[ch] = max(dp[ch], dp[t] + 1) t为a-z,且t和ch可以相邻。这样,在从头到尾扫描完一遍字符串,得到dp数组之后,最少需要删除的字符的个数就等于 n(原来字符串长度) - max(dp[c]).
#include<stdio.h> #include<string> #include<iostream> #include<algorithm> #include<functional> #include<queue> #include<vector> #include<set> #include<list> #include<unordered_map> #include<unordered_set> #include<stack> #include<map> #include<algorithm> #include<string.h> using namespace std; char str[1000005]; int dp[26]; int n; bool table[26][26]; int main(){ scanf("%d", &n); scanf("%s", str); memset(dp, -1, sizeof(dp)); int k; scanf("%d", &k); char word[4]; for (int i = 0; i < k; i++){ scanf("%s", word); table[word[0] - 'a'][word[1] - 'a'] = true; table[word[1] - 'a'][word[0] - 'a'] = true; } for (int i = 0; i < n; i++){ int cur = str[i] - 'a'; int tmp = 1; for (int j = 0; j < 26; j++){ if (table[cur][j]) continue; tmp = max(tmp, dp[j] + 1); } dp[cur] = tmp; } int tmp = 0; for (int i = 0; i < 26; i++) tmp = max(tmp, dp[i]); printf("%d\n", n - tmp); return 0; }
相关文章推荐
- 微软2017校招编程题 Composition(DP)
- 2017微软秋季校园招聘在线编程笔试-#1400 : Composition
- 微软2017校招笔试题3 registration day
- 2017微软秋季校园招聘在线编程笔试 题目2 Composition
- 2017微软秋季校园招聘在线编程笔试 Composition (DP)
- 2017微软秋季校园招聘在线编程笔试 Composition
- 微软2016校招笔试题
- 2017京东校招笔试编程题--python
- 微软2016校招4月在线笔试——第一题 Font Size
- 微软2016校招笔试 第一场部分题目个人思路
- 欢聚时代2017校招笔试题目(JAVA基础类)A卷--8
- 凑硬币(2017腾讯校招笔试题)
- 最大差值(2017某计算机校招笔试试题)
- 【hihocoder】1237 : Farthest Point 微软2016校招在线笔试题
- [2017腾讯校招在线笔试题]
- hihocoder #1094 : Lost in the City微软苏州校招笔试 12月27日 (建图不大【暴力枚举】 子图的4种形态 1Y )
- 水水微软苏州校招笔试 1月17日 题解..
- 魔法城市路径问题(腾讯2017校招笔试题)
- 微软苏州校招笔试 12月27日 By Java
- 今日头条2017校招笔试题