CF_2154_C1. No Cost Too Great (Easy Version)
题目链接:Problem - C1 - Codeforces
题目大意:
给一个长度为n的数组a,b,在此版本中b[i]恒为1
您将执行以下操作任意次数(可能没有):
- 选择一个整数 i (1≤ i ≤ n),并将 a[i] 加 1 。它的代价为 b[i] = 1
求:最小操作数,使得 gcd(a[i] , a[j]) > 1
思路:
当 数组a 存在两个数的 gcd>1 时,答案是0,
当 数组a 全部是互质时,要使 gcd>1,随便找 2个 数 +1 即可;
不难想到,答案区间是在 [0 , 2];
做法:
先预处理一遍每个数的因子,并存起来,
遍历每个 a[i] 的因数,如果某个因数出现 两次 ,说明数组a中 存在两个数的 gcd>1,输出 0 即可,
若没找出现两次的因数,那么让 a[i] -> a[i]+1 ,同样如果某个因数出现 两次,输出1即可,
若上述两种都没找到,输出2即可
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;
const int N = 200086, mod = 998244353;
int n, m;
int a[N], b[N];
vector<int> q[N];
void init() {
for (int i = 2; i < N; i++) {
if (q[i].size()) continue;
for (int j = i; j < N; j += i) q[j].push_back(i);
}
}
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) cin >> b[i];
int res = 2;
map<int, int> cnt;
for (int i = 1; i <= n; i++) {
for (auto x : q[a[i]]) {
cnt[x]++;
if (cnt[x] > 1) res = 0;
}
}
for (int i = 1; i <= n; i++) {
for (auto x : q[a[i]]) cnt[x]--; //清除这个数的因子
for (int x : q[a[i] + 1]) {
if (cnt[x] > 0) res = min(res, 1ll);
}
for (int x : q[a[i]]) cnt[x]++;//复原
}
cout << res << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
init();
int T = 1;
cin >> T;
while (T--) solve();
return 0;
}

浙公网安备 33010602011771号