题目描述
There is a fishing game as following:
-
The game contains nn stages, numbered from 11 to nn.
-
There are four types of stages (numbered from 00 to 33):
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 x 105) — the number of test cases.
There are two lines in each test. The first line contains one integer n (1 ≤ n ≤ 2 x 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 x 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
备注
One possible scenario you can catch two fishes is as follow:
stage 1: Do nothing.
stage 2: Make a pack of fish bait.
stage 3: Catch a fish by a pack of fish bait.
stage 4: Catch the fish that appears in the stage.
代码:
#include <bits/stdc++.h>
using namespace std;
char stage[2000010];
int main()
{
int n;
cin >> n;
for(int i = 0;i < n;i++){
int th;// 阶段数
cin >> th;
scanf("%s",stage);// 阶段类型
long long fish = 0;
long long er = 0;// 鱼饵数量
long long type0 = 0;//0型阶段数量
for(int j = 0;j < th;j++){
if(stage[j] == '0'){
type0++;
}
}
for(int j = 0;j < th;j++){
int s = stage[j] - '0';
if(s == 1){
if(er != 0 &&er > type0){
fish++;
er--;
}
else{
er++;
}
}
else if(s == 2){
fish++;
}
else if(s == 3){
fish++;
}
else if(s == 0){
if(er > 0){
er--;
fish++;
}
type0--;
}
}
cout << fish << endl;
}
}