题解:P11267 【MX-S5-T1】王国边缘
为了方便我们从
考虑倍增。设
考虑
先令
分类讨论
举个例子。
-
-
-
注意到每个完整段都是相同的,都是 $S$。所以我们只需要判最后一个完整段即可。~~式子有一坨懒得打了。~~
然后就差不多做完了。细节还是很多的。推荐一道相似的答辩题 AT_abc346_f,也有这么一坨分类讨论。
一个细节:
代码:
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const int N = 2e5 + 10, P = 1e9 + 7;
int n, q;
ll m;
char s[N];
int sum[N];
int st_n[N][63], st_P[N][63];
int mod_n(int a) {
return a < n ? a : a - n;
}
int mod_P(int a) {
return a < P ? a : a - P;
}
int calc(const int l, const int r) {
// 查询 [l, r] 中最后一个 1 的位置。
int lo = l, hi = r, res = -1;
while (lo <= hi) {
const int mid = lo + hi >> 1;
if (sum[r] - sum[mid - 1]) {
res = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return res;
}
ll get(const int x) {
// 从 x 开始移动一次,位置的偏移量
if (x + m < n) {
int res = calc(x + 1, x + m);
return res == -1 ? 1 : res - x;
}
if (x + m >= 2 * n) {
// 至少经过完整一段
int res = calc(0, (x + m) % n);
if (~res) {
if ((x + m) % n == n - 1) {
return n - 1 - x + (m - n + 1 + x) / n * n;
}
return n - 1 - x + (m - n + 1 + x) / n * n + res + 1;
}
res = calc(0, n - 1);
if (~res) {
return n - 1 - x + ((m - n + 1 + x) / n - 1) * n + res + 1;
}
return 1;
}
// 一段前缀和一段后缀
int res = calc(0, m - n + x);
if (~res) {
return res + 1 + n - 1 - x;
}
res = calc(x + 1, n - 1);
if (~res) {
return res - x;
}
return 1;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m >> q;
for (int i = 0; i < n; ++ i ) {
cin >> s[i];
sum[i] = sum[i - 1] + s[i] - '0';
}
for (int i = 0; i < n; ++ i ) {
ll t = get(i);
st_n[i][0] = t % n;
st_P[i][0] = t % P;
}
for (int j = 1; j < 63; ++ j ) {
for (int i = 0; i < n; ++ i ) {
st_n[i][j] = mod_n(st_n[i][j - 1] + st_n[mod_n(i + st_n[i][j - 1])][j - 1]);
st_P[i][j] = mod_P(st_P[i][j - 1] + st_P[mod_n(i + st_n[i][j - 1])][j - 1]);
}
}
while (q -- ) {
ll s, k;
cin >> s >> k;
s -- ;
int res_n = 0, res_P = 0;
for (int i = 62; ~i; -- i ) {
if (k >= (1ll << i)) {
k -= 1ll << i;
int ans_n = st_n[(s + res_n) % n][i];
int ans_P = st_P[(s + res_n) % n][i];
res_n = mod_n(res_n + ans_n);
res_P = mod_P(res_P + ans_P);
}
}
cout << (s + res_P + 1) % P << '\n';
}
return 0;
}