---
# System prepended metadata

title: L7-Fish
tags: [Codility_lessons]

---

# L7-Fish
###### tags: `Codility_lessons`
## Question
https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/
## Key
1. 利用一個stack將往上游(符合正序loop的方向)的魚存入
2. 熟悉stack STL語法
## Reference
## Solution
```cpp=
#include <stack>

int solution(vector<int> &A, vector<int> &B) {

    if(A.size() == 1)
        return 1;
    int alive = A.size();
    
    stack<int> F;
    
    for(size_t i = 0; i<A.size(); i++) {
        if(B[i] == 1) {
            F.push(i);
        }
        else if(B[i] == 0 && !F.empty()) {
            while(!F.empty() && A[F.top()] < A[i]) {
                F.pop();
                alive--;
            }
            
            if(!F.empty() && A[F.top()] > A[i])
                alive--;
        }
    }
    
    return alive;
}
```

