Time to Raid Cowavans
题意
一个长度为 n n n 的数组 a
,给出 q q q 个询问,询问给出两个值 p o s , x pos, x pos,x ,要求给出 a p o s + a p o s + x + a p o s + 2 ⋅ x + … a_{pos} + a_{pos + x} +a_{pos + 2 \cdot x} + \dots apos+apos+x+apos+2⋅x+… 的值。
题解
- B = n B = \sqrt n B=n ,如果 x ≥ B x \ge B x≥B ,那么直接暴力即可,复杂度 O ( n x ) < O ( n ) O(\frac{n}{x}) < O(\sqrt n) O(xn)<O(n) ;
- 那么剩下不同的 x x x 小于 B B B 个,离线询问,按照 x x x 排序,对相同的 x x x ,处理出 s u m [ i ] sum[i] sum[i] 表示 p o s = i pos = i pos=i 时的答案,处理的复杂度为 O ( n ) O(n) O(n) 。
- 总复杂度为 O ( n ⋅ n ) O(n\cdot \sqrt n) O(n⋅n) 。
代码
#include <bits/stdc++.h>
#define rep(i, a, n) for (int i = a; i <= n; ++i)
#define per(i, a, n) for (int i = n; i >= a; --i)
#ifdef LOCAL
#include "Print.h"
#define de(...) W('[', #__VA_ARGS__,"] =", __VA_ARGS__)
#else
#define de(...)
#endif
using namespace std;
typedef long long ll;
const int maxn = 3e5 + 5;
int n, q, B;
ll a[maxn], ANS[maxn];
struct query {
int pos, x, id;
} Q[maxn];
int solve() {
scanf("%d", &n);
B = sqrt(n);
rep(i, 1, n) scanf("%lld", &a[i]);
scanf("%d", &q);
auto cul1 = [&](int pos, int x) {
ll ans = 0;
for (int i = pos; i <= n; i += x) ans += a[i];
return ans;
};
vector<query> v;
rep(i, 1, q) {
scanf("%d%d", &Q[i].pos, &Q[i].x), Q[i].id = i;
if (Q[i].x >= B) ANS[i] = cul1(Q[i].pos, Q[i].x);
else v.push_back(Q[i]);
}
sort(v.begin(), v.end(), [](const query &A, const query &B) {
return A.x < B.x;
});
vector<ll> sum(n * 2 + 5); // 以i为pos计算答案
for (int i = 0; i < v.size(); ++i) {
auto cul2 = [&](int x) {
for (int i = n; i >= 1; --i)
sum[i] = sum[i + x] + a[i];
};
if (!i || v[i].x != v[i - 1].x) cul2(v[i].x);
ANS[v[i].id] = sum[v[i].pos];
}
rep(i, 1, q) printf("%lld\n", ANS[i]);
return 0;
}
int main() {
#ifdef LOCAL
freopen("in.in", "r", stdin);
freopen("out.out", "w", stdout);
#endif
int T = 1;
// scanf("%d", &T);
while (T--) solve();
return 0;
}