Pair of Numbers

Pair of Numbers

Created by LXC on Tue Jun 27 00:03:55 2023

https://codeforces.com/problemset/problem/359/D

ranting: 2000

tag: binary search, brute force, data structures, math, two pointers

problem

给出一个数组$a_1, a_2, \cdots, a_n$。求所有最大的好子数组。

好子数组是一个子数组中任意值能被子数组中某个值整除。

solution

实际上就是区间中的最小值就是区间的最大公约数。

用st表维护,便可$O(1)$判断区间是否为好区间。

接下来用二分法求出最大好区间的大小。

再用滑动窗口求出所有最大好区间。

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

#include <bits/stdc++.h>
#define SINGLE_INPUT
#define ll long long
#define ull unsigned long long
#define N 500005
#define MOD 998244353
using namespace std;

#define MAXN 300005
int st[MAXN][20]; // st[i][j] 代表区间[i, i+2^j)最小值
int st_g[MAXN][20]; // st_g[i][j] 代表区间[i, i+2^j)gcd

void ST(const vector<int>& a) {
int n = a.size();
for (int i = 0; i < n; i++)
st[i][0] = st_g[i][0] = a[i];
for (int j = 1; (1 << j) <= n; j++) { // 区间大小
for (int i = 0; i + (1 << j) - 1 < n; i++) { // 区间下限
st[i][j] = min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
st_g[i][j] = __gcd(st_g[i][j - 1], st_g[i + (1 << (j - 1))][j - 1]);
}
}
}

bool ask(int l, int r) {
int k = 0;
while ((1 << (k + 1)) <= r - l + 1)
k++;
return min(st[l][k], st[r - (1 << k) + 1][k]) ==
__gcd(st_g[l][k], st_g[r - (1 << k) + 1][k]);
}

void sol() {
int n;
cin >> n;
vector<int> a(n);
for (int& i : a)
cin >> i;
ST(a);
int l = 1, r = n + 1;
while (l < r) {
int m = l + r >> 1;
int ok = 0;
for (int i = m - 1; i < n; i++) {
int j = i - m + 1; // [j, i]
if (ask(j, i)) {
ok = 1;
break;
}
}
if (ok) {
l = m + 1;
} else {
r = m;
}
}
int sz = r - 1;
vector<int> ans;
for (int i = sz - 1; i < n; i++) {
int j = i - sz + 1; // [j, i]
if (ask(j, i))
ans.push_back(j);
}
cout << ans.size() << " " << sz - 1 << "\n";
for (auto i : ans) {
cout << i + 1 << " ";
}
}

int main() {
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifndef SINGLE_INPUT
int t;
cin >> t;
while (t--) {
sol();
}
#else
sol();
#endif
return 0;
}