题目:
Problem Description
Given an array of size n that has the following specifications:
-
Each element in the array contains either a monkey or a banana.
-
Each monkey can eat only one banana.
-
A monkey cannot eat a banana which is more than K units away from the monkey.
We need to find the maximum number of bananas that can be eaten by monkeys.
Input
Two lines.
The first line contains an array of size n contain chars 'B' (represent Banana) or 'M' (represent Monkey). n >= 0.
The second line contains a integer K, K >= 0.
Output
An integer, the maximum number of bananas can be eaten by monkeys.
Sample Input
M B B M B
1
Sample Output
2
代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<sstream>
#include<vector>
using namespace std;
int main() {
string line;
int k = 0, record = 0,eat_number=0;
char left = '.',x='.';
vector<char> sequence;
getline(cin, line);
stringstream ss(line);
while (ss >> x) {
sequence.push_back(x);
}
cin >> k;
for (int i = 0; i < sequence.size(); i++) {
if (sequence[i] == 'M') {
if (record > 0) {
eat_number++;
for (int j = max(0, i - k); j < i; j++) {
if (sequence[j] == 'B') {
sequence[j] = '.';
break;
}
}
sequence[i] = '.';
}
record--;
}
else {
if (record < 0) { eat_number++;
for (int j = max(0,i - k); j < i; j++) {
if (sequence[j] == 'M') {
sequence[j] = '.';
break;
}
}
sequence[i] = '.';
}
record++;
}
if (i >= k) {
left = sequence[i - k];
if (left == 'M') {
record -= -1;
}
else if (left == 'B') {
record -= 1;
}
}
}
cout << eat_number;
return 0;
}
思路:
维持一个大小为k的窗口,如果发生了eat的动作,就把窗口内的B和M都置为'.',以防后面移除时对窗口的record数值造成的影响。