【贪心算法】Monkeys and Bananas

本文详细解析了一道经典的算法题目——猴子吃香蕉问题。题目要求在给定的数组中,猴子只能吃距离它不超过K单位的香蕉,目标是找出最多能有多少香蕉被吃掉。文章提供了完整的代码实现,包括输入输出的格式,以及解决此问题的算法思路。

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

原题地址:

UOJ#52

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
class Solution {
public:
    int maxBananas(int k, vector<char>& arr){
        if (k == 0)     // 若猴子可以吃到香蕉的范围为0,则直接返回0个即可
            return 0;
        n = arr.size();
        for(int i = 0;i < n;i++){
            if(arr[i] == 'M'){
                // 观察该猴子以k为半径从左数第k个到右数第k个,是否有香蕉,有则计数,并抹去对于索引的香蕉
                for(int j = -k;j <= k;j++)
                    if((i + j >= 0) && (arr[i + j] == 'B')){
                        arr[i+j] = '0';
                        maxCnt ++;
                        break;  // 只要吃到,就跳出循环,因为每个猴子最多只能吃一个香蕉
                    }
            }
        }
        return maxCnt;
    }
private:
    int n, maxCnt = 0;  // n数组长度,maxCnt所有猴子吃到最多的香蕉个数
};
int main(){
    int k;
    char element;
    vector<char> arr;
    while (cin.peek()!='\n'){
        cin >> element;
        arr.push_back(element);
    }
    cin >> k;
    Solution sol;
    cout<<sol.maxBananas(k, arr)<<endl;
    return 0;
}

在这里插入图片描述

当然可以!下面是一个**结构相似、主题丰富、适合训练 Word2Vec 模型**的 `sentences` 列表,包含以下几类句子: - 动物行为 - 食物特征 - 日常生活 - 情感与动作 - 自然与天气 - 人物与职业 --- ### ✅ 生成的 `sentences` 列表如下: ```python sentences = [ # 动物行为 "dogs chase cats", "cats drink milk", "dogs love bones", "cats hate water", "dogs bark loudly", "cats climb trees", "dogs play fetch", "cats purr softly", "dogs guard houses", "cats hunt mice", "dogs wag tails", "cats nap all day", "birds fly high", "fish swim fast", "birds sing in morning", "tigers roar at night", "elephants walk slowly", "monkeys swing on trees", # 食物特征 "apples are sweet", "bananas taste creamy", "apples grow on trees", "bananas have peels", "apples make juice", "bananas are yellow", "apples can be red", "bananas rich in potassium", "oranges are juicy", "grapes are sour", "strawberries are red", "bread is soft", "cheese tastes salty", "eggs are nutritious", "rice is sticky", "noodles are long", "chocolate is sweet", # 日常生活 "kids eat apples", "monkeys love bananas", "dogs enjoy meat", "cats prefer fish", "people drink milk", "children like fruit", "breakfast has milk", "dogs drink water", "cats avoid dogs", "people walk to work", "buses run on time", "cars drive fast", "students study hard", "teachers explain clearly", "doctors help patients", "cooks prepare meals", "babies cry at night", "seniors rest peacefully", # 情感与动作 "he feels happy", "she looks tired", "they laugh together", "he cries softly", "she dances gracefully", "they argue loudly", "he hugs his dog", "she kisses her baby", "they shake hands", "he smiles kindly", "she yells in anger", "they cheer with joy", # 自然与天气 "sun rises early", "moon shines at night", "stars twinkle above", "clouds float in sky", "rain falls gently", "wind blows strongly", "snow covers mountains", "ice melts in sun", "lightning flashes bright", "thunder rumbles loudly", "fog covers the fields", "dew drops sparkle", # 人物与职业 "doctors heal patients", "teachers teach students", "engineers build bridges", "writers write stories", "artists draw pictures", "singers sing songs", "actors perform plays", "pilots fly planes", "farmers grow crops", "chefs cook meals", "drivers drive cars", "scientists make discoveries", # 更多组合 "apple pie is delicious", "banana smoothie is healthy", "dog food contains nutrients", "cat food has tuna flavor", "apple and banana salad", "dog and cat live together", "milk with banana shake", "fish for cat dinner", "bread with cheese", "rice with chicken", "noodles with beef", "coffee with milk", "tea with sugar", "juice with ice" ] ``` --- ## ✅ 使用说明 你可以将上面的 `sentences` 列表直接替换你项目中的原始 `sentences` 数据,用于训练 Word2Vec 模型,例如: ```python word_sequence = " ".join(sentences).split() vocab = list(set(word_sequence)) voc_size = len(vocab) word2idx = {w: i for i, w in enumerate(vocab)} ``` 这样训练出来的词向量将能更好地捕捉以下语义关系: - 同类动物之间的关系(如 dogs 和 cats) - 食物之间的关系(如 apples 和 bananas) - 人物与动作的关系(如 doctors 和 heal) - 自然现象之间的关系(如 rain 和 clouds) --- ##
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SL_World

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值