题解:CF2005D Alter the GCD
Solution
可能比较简单的写法。
令
倒序枚举
复杂度
Code
#include <bits/stdc++.h>
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
using namespace std;
namespace Milkcat {
typedef long long LL;
typedef pair<LL, LL> pii;
const int N = 2e5 + 5;
struct node {
int A1, A2, B1, B2;
node mdf(int x, int y) const { return {__gcd(A1, x), A2, __gcd(B1, y), B2}; }
int calc(int x, int y) const { return __gcd(x, __gcd(B1, A2)) + __gcd(y, __gcd(A1, B2)); }
bool operator < (node x) const {
return make_tuple(A1, A2, B1, B2) < make_tuple(x.A1, x.A2, x.B1, x.B2);
}
};
int n, rs, a[N], b[N], pr1[N], pr2[N]; LL ct; map<node, int> s;
void upd(int x, int y) {
if (rs < x) rs = x, ct = 0;
if (rs == x) ct += y;
}
int main() {
cin >> n, rs = 0, s.clear();
REP(i, 1, n) cin >> a[i], pr1[i] = __gcd(pr1[i - 1], a[i]);
REP(i, 1, n) cin >> b[i], pr2[i] = __gcd(pr2[i - 1], b[i]);
int sf1 = 0, sf2 = 0;
DEP(i, n, 1) {
map<node, int> t;
for (auto [x, y] : s)
t[x.mdf(a[i], b[i])] += y;
t[{a[i], sf1, b[i], sf2}] ++;
for (auto [x, y] : t)
upd(x.calc(pr1[i - 1], pr2[i - 1]), y);
s.swap(t), sf1 = __gcd(sf1, a[i]), sf2 = __gcd(sf2, b[i]);
}
cout << rs << ' ' << ct << '\n';
return 0;
}
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int T = 1; cin >> T;
while (T --) Milkcat::main();
return 0;
}