跳到正文

题解

题解:CF2005D Alter the GCD

喵仔牛奶约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月5日
篇幅
约 4 分钟
题目
CF2005D

版本

  1. v1当前

Solution

可能比较简单的写法。

令 f(a,l,r)f(a,l,r) 为 al,al+1,⋯ ,ara_l,a_{l+1},\cdots,a_r 的 gcd⁡\gcd,l>rl>r 则为 00。

倒序枚举 ll,可以发现对于所有 rr,四元组 (f(a,l,r),f(a,r+1,n),f(b,l,r),f(b,r+1,n))(f(a,l,r),f(a,r+1,n),f(b,l,r),f(b,r+1,n)) 只有 O(log⁡V)\mathcal O(\log V) 种。使用 map 维护所有可能的四元组及其个数即可。

复杂度 O(nlog⁡2V)\mathcal O(n\log^2V)。

Code

C++
#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;
}
原文