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.

說明

這題可以直接把數學式列出來。

最後時空複雜度都是 $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 <iostream>
#include <vector>

using namespace std;

bool check(const vector<int64_t>& arr) {
    size_t n = arr.size();
    vector<int64_t> 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<int64_t> arr(n);

        for (auto& ai : arr) {
            cin >> ai;
        }

        cout << (check(arr) ? "YES" : "NO") << endl;
    }
    return 0;
}