codeforces 798 C. Mike and gcd problem(贪心+思维+数论)

时间:2023-03-09 17:21:52
codeforces 798 C. Mike and gcd problem(贪心+思维+数论)

题目链接:http://codeforces.com/contest/798/problem/C

题意:给出一串数字,问如果这串数字的gcd大于1,如果不是那么有这样的操作,删除ai, ai + 1 并且把 ai - a(i + 1), ai + a(i + 1)

放入原来的位置。问是否能够在几步操作后使得串的gcd大于1然后要求最小的操作数。

题解:偶数=偶数*偶数 or 奇数*偶数,奇数=奇数*奇数。

如果整个字符串全是偶数的话肯定gcd是大于1的。介于题目要求的操作,奇数-(or)+奇数=偶数

奇数-(or)+偶数=奇数,但是操作两次就是偶数。所以只要把原来串中的奇数改成偶数就行了。

因为影响gcd结果的就是奇数。然后贪心一下就行了。先处理两个奇数连在一起的然后再考虑一奇一

偶的。

#include <iostream>
#include <cstring>
using namespace std;
const int M = 1e5 + 10;
int a[M];
int gcd(int x , int y) {
return x % y ? gcd(y , x % y) : y;
}
int main() {
int n;
cin >> n;
for(int i = 0 ; i < n ; i++) {
cin >> a[i];
}
int num = 0;
for(int i = 0 ; i < n ; i++) {
num = gcd(num , a[i]);
}
if(num > 1) {
cout << "YES" << endl;
cout << 0 << endl;
}
else {
int ans = 0;
for(int i = 1 ; i < n ; i++) {
if(a[i] % 2 != 0 && a[i - 1] % 2 != 0) {
ans++;
a[i] = 2;
a[i - 1] = 2;
}
}
for(int i = 0 ; i < n ; i++) {
if(i == n - 1) {
if(a[i] % 2 != 0) {
ans += 2;
a[i] = 2;
}
}
else {
if(a[i] % 2 != 0) {
ans += 2;
a[i] = 2;
}
}
}
cout << "YES" << endl;
cout << ans << endl;
}
return 0;
}