Fairies love to pick medicine

Title description:

The volume of a backpack is V, a string s is given, and the length is n.
Then s[i] represents the volume of the item on the i-th day, which is 1 or 2.
On day i, you can choose whether to put item i in the backpack. If the backpack capacity is not enough, you can first
take out some items from it.
Each item in the backpack before the end of the day will produce a pill.
Ask how many pills are there at the end of n days.
Insert picture description here

Sample

Insert picture description here

For the fourth set of examples

On the first day, a volume of 2 was loaded, and the number of pills produced on that day was 1.

On the second day, a volume of 1 medicine was loaded, and the number of pills produced on that day was 2.

On the third day, the medicine with a volume of 2 was taken out, and the medicine with a volume of 1 was loaded. The number of pills produced on that day was 2.

There was no operation on the fourth day, and the number of pills produced was 2.

On the fifth day, the medicine with a volume of 1 is loaded, and the number of pills produced on that day is 3

So 1+2+2+2+3=10

statement

  • ans result (maximum)
  • cnt1: the number of volume 1
  • cnt2: quantity with volume 2
  • v: the size of the backpack
  • n: length of the string
  • char s[101111]: character string

main

  • cin>>v>>s;
  • n=strlen(s)
  • Iterate over the string
  • If s[i]=='2' can be put (because it is a string, so '2')
    Insert picture description here
  • If s[i]=='1' can still be put, just put it, can't put it down (that is, it is full) to see if there is a medicinal material of volume 2 in it, if there is cnt2–,cnt1++, because this can free up a volume

Insert picture description here
Insert picture description here

  • One day's pills
    Insert picture description here
  • Final output

Code

#include <iostream>
using namespace std;
long long ans,cnt1,cnt2,v,n;
char s[101111];
int main()
{
    cin>>v>>s;
    n=strlen(s);
    for(int i=0;i<n;i++){
        if(s[i]=='2'){
            if(cnt1+2*cnt2+2<=v)cnt2++;
        }else{
            if(cnt1+2*cnt2+1<=v)cnt1++;
            else if(cnt2>0)cnt1++,cnt2--;
            }
        ans+=cnt1+cnt2;
    }
    cout <<ans<< endl;
    return 0;
}

victory

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45618376/article/details/114850979