1693A - Directional Increase
題目
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:
- 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.
- 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.
說明
這題可以直接把數學式列出來。
點 去 點記為 次, 點回 點記為 次。 - 由於最後要回到 1 ,所以
- 根據出去回來要+1-1,
=>
- if
, then (因為無法過去) - 所以可以依序把
算出來,然後檢查條件。
最後時空複雜度都是
Code
cpp
#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;
}