codeforces 798C Mike and gcd problem
C.Mike and gcd problem
Mike has a sequence A?=?[a1,?a2,?...,?an] of length n. He considers the sequence B?=?[b1,?b2,?...,?bn] beautiful if the gcd of all its elements is bigger than 1, i.e. .
Mike wants to change his sequence in order to make it beautiful. In one move he can choose an index i
Input
The first line contains a single integer n (2?≤?n?≤?100?000) — length of sequence A.
The second line contains n space-separated integers a1,?a2,?...,?an (1?≤?ai?≤?109) — elements of sequence A.
Output
Output on the first line "YES" (without quotes) if it is possible to make sequence A
If the answer was "YES", output the minimal number of moves needed to make sequenceA beautiful.
Example
Input2Output
1 1
YESInput
1
3Output
6 2 4
YESInput
0
2Output
1 3
YES
1
note
In the first example you can simply make one move to obtain sequence [0,?2] with .
In the second example the gcd of the sequence is already greater than 1.
解題思路:
題意為:輸入給定數字,求他們的大於1的最大公約數,如果沒有則進行操作
對數字a,b進行操作: a,b a-b,a+b -2b,2a
由上可知,不論兩個數字為什麽,最多操作兩次就有公約數2
那麽有三種情況:1.都為偶數,不需要進行操作。2.一個為奇數一個為偶數,需要操作兩次,3.都為奇數,只需操作一次;
然後隨便打下就行了
實現代碼:
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); } int main() { ll m,a[100005],i,ans,num; cin>>m; num = 0; for(i=1;i<=m;i++) cin>>a[i]; ans = gcd(abs(a[1]),abs(a[2])); for(i=3;i<=m;i++) ans = gcd(ans,abs(a[i])); if(ans>1) cout<<"YES"<<endl<<"0"<<endl; else { for(i=1;i<m;i++) if(a[i]%2&&a[i+1]%2) { a[i]=0;a[i+1]=0;num++; } for(i=1;i<m;i++) if((a[i]%2==0&&a[i+1]%2)||(a[i]%2&&a[i+1]%2==0)) { a[i]=0;a[i+1]=0;num+=2; } cout<<"YES"<<endl<<num<<endl; } return 0; }
codeforces 798C Mike and gcd problem