学校OJ题:Monkeys and Bananas

题目:

Problem Description

Given an array of size n that has the following specifications:

  1. Each element in the array contains either a monkey or a banana.

  2. Each monkey can eat only one banana.

  3. 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数值造成的影响。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值