2020牛客暑期多校训练营(第三场)A.Clam and Fish

2020牛客暑期多校训练营(第三场)A.Clam and Fish

题目链接

题目描述

There is a fishing game as following:

The game contains nn stages, numbered from 1 to n.

There are four types of stages (numbered from 0 to 3):

type 0: There are no fish and no clam in this stage.

type 1: There are no fish and one clam in this stage.

type 2: There are one fish and no clam in this stage.

type 3: There are one fish and one clam in this stage.

In each stage, you can do exactly one of the following four actions.

If there is a clam in the stage, you can use this clam to make one pack of fish bait. And the number of packs of fish bait you have is increased by one. You can use this pack of fish bait to catch fish after this stage.

If there is one fish in the stage, you can catch this fish without any fish bait. After this stage, the number of packs of fish bait you have is not changed.

If you have at least one pack of fish bait. You can always catch one fish by using exactly one pack of fish bait even if there are no fish in this stage. After this stage, the number of packs of fish bait you have is decreased by one.

You can do nothing.

Now, you are given nn and the type of each stage. Please calculate the largest number of fish you can get in the fishing game.

输入描述:

The first line contains one integer t ( 1 ≤ t ≤ 2.5 × 1 0 5 t (1 \le t \le 2.5 \times 10^5 t(1t2.5×105) — the number of test cases.

There are two lines in each test. The first line contains one integer n ( 1 ≤ n ≤ 2 × 1 0 6 ) n (1 \le n \le 2 \times 10^6) n(1n2×106), indicating the number of stages in this game. The second line contains a string with length n. The i-th character of this string indicates the type of the i-th stage.

The sum of n across the test cases doesn’t exceed 2 × 1 0 6 2 \times 10^6 2×106 .

输出描述:

For each test case print exactly one integer — the maximum number of fish you can catch in the game configuration.

示例1

输入

2
4
0103
1
1

输出

2
0

思维题,我们考虑如何获得捕获最多的鱼:
1.对 0 0 0,有饵就捕鱼
2.对 2 2 2 3 3 3,直接选择捕鱼,不浪费鱼饵
3.对 1 1 1,可以捕鱼也可以做鱼饵,我比赛时是判断该位置后面 0 0 0 的数量来看选择哪一种的,但是看了别人的代码好像更加简单,就是默认制饵,最后加上剩下的鱼饵数除 2 2 2 就是答案,可以当作一半用来制饵,一半用来捕鱼。
AC代码如下:

#include
using namespace std;
typedef long long ll;
const int N=2e6+5;
int main(){
    int n,t;
    char s[N];
    scanf("%d",&t);
    while(t--){
        scanf("%d%s",&n,s);
        int ans=0,sum=0;
        for(int i=0;i<n;i++){
            if(s[i]=='0'){
                if(sum) sum--,ans++;
            }
            else if(s[i]=='1') sum++;
            else ans++;
        }
        printf("%d\n",ans+sum/2);
    }
    return 0;
}

你可能感兴趣的:(思维,牛客)