A-Clam and Fish(贪心)

题目链接:https://ac.nowcoder.com/acm/contest/5668/A
简要题意:
小月有n单位的时间都在钓鱼,每个单位时间有4种状态,有蛤蜊/没蛤蜊,有鱼/没鱼。小月事先知道这n个时间点的状态。每个时间点有四种可能的动作:
1.若该时间点有鱼,则可以直接钓鱼。
2.若该时间点有蛤蜊,则可以用该蛤蜊制作一个鱼饵。
3.若该时间点身上有至少一个鱼饵,则可以用一个鱼饵钓一条鱼,钓完后就少了一个鱼饵。
4.什么都不做。

请问小月最多可以钓多少条鱼。

解题思路:
贪心,从时间早考虑到时间晚,有蛤蜊的时候就做鱼饵,没蛤蜊的时候就尝试用鱼饵钓鱼,最后若发现有x包鱼饵,就把制作比较晚的x/2包鱼饵的时间拿来钓鱼。我当时的想法与此相同,不过我是在过程中去维护后面有多少1,搞得自己很麻烦。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e6+7;
char s[maxn];
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        scanf("%d",&n);
        scanf("%s",s);
        int ans= 0, res = 0;
        for(int i = 0; i < n; i++) {
            if(s[i] == '2' || s[i] == '3')
                ans++;
            else if(s[i] == '0')
            {
                if(res != 0)
                    res--, ans++;
            }
            else {
                res++;
            }
        }
        if(res) res/=2;
        ans+=res;
        printf("%d\n",ans);
    }
}
全部评论

相关推荐

点赞 评论 收藏
转发
1 收藏 评论
分享
牛客网
牛客企业服务