# 1693A. Directional Increase

#Implementation

## 題目

Codeforces: 1693A: Directional Increase

We have an array of length n. Initially, each element is equal to 0 and there is a pointer located on the first element.

We can do the following two kinds of operations any number of times (possibly zero) in any order:

1. If the pointer is not on the last element, increase the element the pointer is currently on by 1. Then move it to the next element.
2. If the pointer is not on the first element, decrease the element the pointer is currently on by 1. Then move it to the previous element.

But there is one additional rule. After we are done, the pointer has to be on the first element.

You are given an array a. Determine whether it’s possible to obtain a after some operations or not.

## 說明

• $i$ 點 去 $i+1$ 點記為 $p_i$ 次，$i+1$ 點回 $i$ 點記為 $q_i$ 次。
• $p_i \geq 0$
• $q_i \geq 0$
• 由於最後要回到 1 ，所以 $p_i = q_i$
• 根據出去回來要+1-1，
• $a_i = p_i - p_{i-1}$ => $p_i = a_i + p_{i-1}$
• $p_1 = a_1# •$p_n = 0$• if$p_i = 0$, then$p_j = 0 \forall j > i$(因為無法過去) • 所以可以依序把$p_i$算出來，然後檢查條件。 最後時空複雜度都是$O(N)\$

## Code

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58  #include #include using namespace std; bool check(const vector& arr) { size_t n = arr.size(); vector p(n); p[0] = arr[0]; for (size_t i = 1; i < n; ++i) { p[i] = p[i - 1] + arr[i]; } // p_i >= 0 for (size_t i = 0; i < n; ++i) { if (p[i] < 0) { return false; } } if (p[n - 1] != 0) { return false; } // if p_i = 0, then p_j = 0 forall j > i size_t bp = 0; while (bp < n && p[bp] > 0) { ++bp; } for (size_t i = bp; i < n; ++i) { if (p[i] != 0) { return false; } } return true; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; for (int lt = 0; lt < T; ++lt) { int n; cin >> n; vector arr(n); for (auto& ai : arr) { cin >> ai; } cout << (check(arr) ? "YES" : "NO") << endl; } return 0; }