2020 Jan Bronze Problem 1 Word Processor
Official Problem StatementEdit
Problem Statement:
Given a text document of length N, you must determine the minimum number of keystrokes needed to type the document.
Solution:
The solution to this problem is to use a dynamic programming approach. We can create a two-dimensional array of size N+1 x N+1, where the first row and column represent the empty string. We then fill the array with the minimum number of keystrokes needed to type the substring from the beginning of the document to the character at position (i, j).
For example, if the document is "abcdef", the array would look like this:
| | | a | b | c | d | e | f | |---|---|---|---|---|---|---|---| | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | | a | 0 | 0 | 1 | 2 | 3 | 4 | 5 | | b | 0 | 0 | 0 | 1 | 2 | 3 | 4 | | c | 0 | 0 | 0 | 0 | 1 | 2 | 3 | | d | 0 | 0 | 0 | 0 | 0 | 1 | 2 | | e | 0 | 0 | 0 | 0 | 0 | 0 | 1 | | f | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
We then use the following recurrence relation to fill the array:
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + 1) for all k in [i, j-1]
where dp[i][j] is the minimum number of keystrokes needed to type the substring from the beginning of the document to the character at position (i, j).
We can then use this array to determine the minimum number of keystrokes needed to type the entire document. The answer is dp[0][N], which is the value in the bottom right corner of the array.
C++ Code:
- include <bits/stdc++.h>
using namespace std;
int main() {
int N; cin >> N; string s; cin >> s; int dp[N+1][N+1]; memset(dp, 0, sizeof(dp)); for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { dp[i][j] = j - i; for (int k = i; k < j; k++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + 1); } } } cout << dp[0][N] << endl; return 0;
}