題目2 : 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
參考答案1:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define fst first
#define snd second
const int MAXN = 100010;
bool can[30][30];
int dp[100010][30];
int main(void) {
int n;
cin >> n;
string s;
cin >> s;
for (int i = 0; i < 26; ++ i) for (int j = 0; j < 26; ++ j) can[i][j] = true;
int m;
cin >> m;
for (int i = 0; i < m; ++ i) {
string t;
cin >> t;
can[t[0]-'a'][t[1]-'a'] = false;
can[t[1]-'a'][t[0]-'a'] = false;
}
memset(dp, 0x3f, sizeof(dp));
vector<int> lst(26, 0);
lst[s[0] - 'a'] = 1;
dp[1][s[0] - 'a'] = 0;
for (int i = 2; i <= n; ++ i) {
for (int j = 0; j < 26; ++ j) {
dp[i][j] = dp[i - 1][j] + 1;
}
int ch = s[i - 1] - 'a';
for (int j = 0; j < 26; ++ j) if (can[ch][j] && lst[j]) {
dp[i][ch] = min(dp[i][ch], dp[lst[j]][j] + i - lst[j] - 1);
}
dp[i][ch] = min(dp[i][ch], i - 1);
lst[ch] = i;
}
int ans = n;
for (int i = 0; i < 26; ++ i) ans = min(ans, dp[n][i]);
cout << ans << endl;
return 0;
}