A. Monkeys and Bananas(贪心系列)

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值