acm专题---动态规划
题目来源:http://hihocoder.com/problemset/problem/1400?sid=983096
#1400 : Composition
描述
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.
输入
The first line contains the length of the composition N.
The second line contains N characters, which make up the composition. Each character belongs to 'a'..'z'.
The third line contains the number of illegal pairs M.
Each of the next M lines contains two characters ch1 and ch2,which cannot be adjacent.
For 20% of the data: 1 ≤ N ≤ 10
For 50% of the data: 1 ≤ N ≤ 1000
For 100% of the data: 1 ≤ N ≤ 100000, M ≤ 200.
输出
One line with an integer indicating the minimum number of characters that need to be deleted.
样例提示
Delete 'a' and 'd'.
- 样例输入
-
5 abcde 3 ac ab de
- 样例输出
-
2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <iostream> using namespace std; #include <vector> #include<algorithm> #include<queue> #include<string> #include<map> #include<math.h> #include<iomanip> #include<stack> int main() { int n; cin>>n; string str; cin>>str; int m; cin>>m; bool flag[26][26]; for ( int i=0;i<26;i++) { for ( int j=0;j<26;j++) flag[i][j]= true ; } for ( int i=0;i<m;i++) { string tmp; cin>>tmp; flag[tmp[0]- 'a' ][tmp[1]- 'a' ]=flag[tmp[1]- 'a' ][tmp[0]- 'a' ]= false ; } int dp[26]; for ( int i=0;i<26;i++) dp[i]=0; dp[0]=1; for ( int i=1;i<n;i++) { int maxnum=0; for ( int j=0;j<26;j++) { if (flag[str[i]- 'a' ][j]) maxnum=max(maxnum,dp[j]+1); } dp[str[i]- 'a' ]=maxnum; } int ans=0; for ( int i=0;i<26;i++) { if (dp[i]>ans) ans=dp[i]; } cout<<n-ans<<endl; return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 《HelloGitHub》第 106 期
· 数据库服务器 SQL Server 版本升级公告
· C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)