This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
namespace std {
template <int D, typename T>
struct Vec : public vector<Vec<D - 1, T>> {
static_assert(D >= 1, "Dimension must be positive");
template <typename... Args>
Vec(int n = 0, Args... args) : vector<Vec<D - 1, T>>(n, Vec<D - 1, T>(args...)) {}
};
template <typename T>
struct Vec<1, T> : public vector<T> {
Vec(int n = 0, T val = T()) : std::vector<T>(n, val) {}
};
/* Example
Vec<4, int64_t> f(n, k, 2, 2); // = f[n][k][2][2];
Vec<2, int> adj(n); // graph
*/
template <class Fun>
class y_combinator_result {
Fun fun_;
public:
template <class T>
explicit y_combinator_result(T &&fun) : fun_(std::forward<T>(fun)) {}
template <class... Args>
decltype(auto) operator()(Args &&...args) {
return fun_(std::ref(*this), std::forward<Args>(args)...);
}
};
template <class Fun>
decltype(auto) y_combinator(Fun &&fun) {
return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
}
/* Example
auto fun = y_combinator([&](auto self, int x) -> void {
self(x + 1);
});
*/
} // namespace std
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++) cin >> a[i];
map<int64_t, int> mp;
vector<vector<int>> prv(__lg(n) + 1, vector<int>(n + 1, -1));
mp[0] = 0;
int64_t sum = 0;
for (int i = 1; i <= n; i++) {
sum += a[i];
if (mp.count(sum)) {
prv[0][i] = mp[sum];
prv[0][i] = max(prv[0][i], prv[0][i - 1]);
} else {
prv[0][i] = prv[0][i - 1];
}
mp[sum] = i;
}
for (int i = 1; i <= __lg(n); i++) {
for (int j = 0; j <= n; j++) {
if (prv[i - 1][j] == -1) continue;
prv[i][j] = prv[i - 1][prv[i - 1][j]];
}
}
int q;
cin >> q;
while (q--) {
int l, r;
cin >> l >> r;
l--;
int res = 0;
for (int i = __lg(n); i >= 0; i--) {
if (r >= l && prv[i][r] >= l) r = prv[i][r], res += 1 << i;
}
cout << res << '\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |