您的位置:首页 > 编程语言

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 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


题解: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微软 秋招