2017微软秋季校园招聘在线编程笔试 Composition (DP)
2016-10-12 13:33
471 查看
#1400 : Composition
时间限制:10000ms单点时限:1000ms
内存限制:256MB
描述
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 beadjacent, '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
题解:DP,dp[i][j]代表 0~i 最后字符为j+‘a’。需要删除的最少字符。
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include<climits>
#include<sstream>
#include<stack>
#include<unordered_map>
#include<list>
using namespace std;
bool mapp[27][27];
int dp[100001][27];
int solve_min(int a,int b) {
if(a==-1) return b;
return a<b?a:b;
}
int main() {
int n,m;
string input;
cin>>n;
cin>>input;
cin>>m;
memset(mapp,false,sizeof(mapp));
memset(dp,-1,sizeof(dp));
for(int i=0;i<m;i++) {
char s,e;
cin>>s>>e;
mapp[s-'a'][e-'a']=mapp[e-'a'][s-'a']=true;
}
dp[0][input[0]-'a']=0;
for(int i=1;i<n;i++) {
int index=input[i]-'a';
dp[i][index]=i;
for(int j=0;j<27;j++) {
if(dp[i-1][j]!=-1) {
dp[i][j]=solve_min(dp[i][j],dp[i-1][j]+1);
if(!mapp[index][j]) {
dp[i][index]=solve_min(dp[i][index],dp[i-1][j]);
}
}
}
}
int res=INT_MAX;
for(int i=0;i<27;i++) {
res=solve_min(dp[n-1][i],res);
}
cout<<res<<endl;
return 0;
}
相关文章推荐
- 2017微软秋季校园招聘在线编程笔试 Composition
- 2017微软秋季校园招聘在线编程笔试-#1400 : Composition
- 2017微软秋季校园招聘在线编程笔试 题目2 Composition
- 2017微软秋季校园招聘在线编程笔试
- 2017微软秋季校园招聘在线编程笔试(第一题)
- 2017微软秋季校园招聘在线编程笔试(第二题)
- 2017微软秋季校园招聘在线编程笔试-#1402 : MS Recognition
- 2017微软秋季校园招聘在线编程笔试-#1401 : Registration Day
- 2017微软秋季校园招聘在线编程笔试(第三题)
- 2017微软秋季校园招聘在线编程笔试
- 2017微软秋季校园招聘在线编程笔试-#1399 : Shortening Sequence
- 【hihocoder1290 微软2016校园招聘4月在线笔试C】【二维DP】 Demo Day 机器人遇到障碍向右走向下走 最少调整数使得左上角走到右下角
- 微软2016校园招聘4月在线笔试 hihocoder 1290 Demo Day (dp)
- 微软2016校园招聘在线笔试 B Professor Q's Software [ 拓扑图dp ]
- 微软2016校园招聘在线笔试 - 第二题 Professor Q's Software
- 微软2016校园招聘9月在线笔试-题目3 : Fibonacci
- Lucky Substrings 微软2016校园招聘在线笔试第二场
- 阿里巴巴2016年秋季校园招聘C++研发岗在线笔试附加题第一题
- 微软2016校园招聘9月在线笔试C.Fibonacci
- hihoCoder 1136 Professor Q's Software 微软2016校园招聘在线笔试