#include <bits/stdc++.h>using namespace std;
const int N = 5e5 + 10;
int n, a[N], p[N];
signed main() {
cin >> n;
for (int i = 1; i <= n; ++ i ) {
cin >> a[i];
p[a[i]] = i;
}
cout << n << ' ';
for (int i = 2; i <= n; ++ i ) {
bool flg = false;
for (int l = 1; l <= n; ++ l ) {
int d = 0;
for (int r = l; r <= n; ++ r ) {
d = __gcd(d, a[r]);
if (d == i && (p[i] < l || p[i] > r)) flg = true;
}
}
cout << (flg ? n : n - 1) << ' ';
}
return 0;
}
O(n2)
C++
#include <bits/stdc++.h>using namespace std;
const int N = 5e5 + 10;
int n, a[N], b[N], p[N];
signed main() {
cin >> n;
for (int i = 1; i <= n; ++ i ) {
cin >> a[i];
p[a[i]] = i;
}
cout << n << ' ';
for (int i = 2; i <= n; ++ i ) {
for (int j = 1; j <= n; ++ j )
b[j] = j != p[i] && a[j] % i == 0 ? a[j] / i : 0;
bool flg = false;
int d = 0;
for (int j = 1; j <= n; ++ j )
if (b[j]) d = __gcd(d, b[j]), flg |= d == 1;
else d = 0;
cout << (flg ? n : n - 1) << ' ';
}
return 0;
}
O(nlogn) 正解
C++
#include <bits/stdc++.h>using namespace std;
const int N = 5e5 + 10;
int n, a[N], b[N], p[N];
vector<int> pos[N];
int st[N][20];
void init() {
for (int i = 1; i <= n; ++ i ) st[i][0] = a[i];
for (int j = 1; j < 20; ++ j )
for (int i = 1; i + (1 << j - 1) <= n; ++ i )
st[i][j] = __gcd(st[i][j - 1], st[i + (1 << j - 1)][j - 1]);
}
int query(int l, int r) {
int k = log2(r - l + 1);
return __gcd(st[l][k], st[r - (1 << k) + 1][k]);
}
signed main() {
cin >> n;
for (int i = 1; i <= n; ++ i ) {
cin >> a[i];
p[a[i]] = i;
}
init();
for (int i = 1; i <= n; ++ i )
for (int j = 2 * i; j <= n; j += i)
pos[i].push_back(p[j]);
for (int i = 1; i <= n; ++ i ) {
sort(pos[i].begin(), pos[i].end());
}
cout << n << ' ';
for (int i = 2; i <= n; ++ i ) {
bool flg = false;
for (int l = 0, r = 1; r < pos[i].size(); ++ r )
if (pos[i][r] == pos[i][r - 1] + 1) {
flg |= query(pos[i][l], pos[i][r]) == i;
}
else l = r;
cout << (flg ? n : n - 1) << ' ';
}
return 0;
}