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
MBBMB
1
Sample Output
2
题解思路
猴子从左到右吃第一个能吃到的香蕉:即左边最远的、右边最近的。
举例说明:对于BBMMB,第一个猴子吃第一个香蕉(第一个能够得到的),如果不吃的话,第一个香蕉后别的猴子可能够不到,因此吃比不吃好。对于MMBB,第一个猴子吃第一个能够到的香蕉,即3号香蕉。那么第二个猴子可以吃后边第三个香蕉。如果第一个猴子将三号香蕉让给二号猴子的话,那么第一个猴子没得吃。也就是说,一号猴子吃三号香蕉不会使结果变得更差(最多吃的香蕉总数)
c++ 代码
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
getline(cin,s);
vector<int> M;
vector<int> B;
for(int i=0;i<s.size();i++)
{
if (s[i]=='M')
M.push_back(i);
if (s[i]=='B')
B.push_back(i);
}
int K;
cin>>K;
int i=0;
int j=0;
int res=0;
while(i<M.size()&&j<B.size()){
if(abs(M[i]-B[j])<=K){
i++;
j++;
res++;
}
else if(M[i]>B[j])
j++;
else
i++;
}
cout<<res<<endl;
return 0;
}