【Codeforces - 798C】 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?(1?≤?i?<?n), delete numbers?ai,?ai?+?1?and put numbers?ai?-?ai?+?1,?ai?+?ai?+?1?in their place instead, in this order. He wants perform as few operations as possible. Find the minimal number of operations to make sequence?A?beautiful if it's possible, or tell him that it is impossible to do so.
?is the biggest non-negative number?d?such that?d?divides?bi?for every?i?(1?≤?i?≤?n).
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?Abeautiful by performing operations described above, and "NO" (without quotes) otherwise.
If the answer was "YES", output the minimal number of moves needed to make sequence?A?beautiful.
Examples
Input
2 1 1Output
YES 1Input
3 6 2 4Output
YES 0Input
2 1 3Output
YES 1Note
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.
題目大意:
給定一個n個元素的數組,求最少幾次操作可以使 gcd( a1, a2,… ,an )>1 。
定義一次操作是:將刪掉,并且加入這兩個數。
解題報告:
首先可以證明:如果你開始操作了,那最終一定要湊出2的倍數。如果公因子d是非2的數,那必須是初始序列。
證明如下:運用反證法,對于任意的a和b,操作之后變成a+b和a-b,假設這個公因子d不是2,最終推出矛盾,也就是證明出g必須為2.
首先需要保證d|(a+b) 且 d|(a-b)。(設為式①和式②)
設公因子是d,則a=k1*d+c1 , b=k2*d+c2(且0<c1,c2<d)。帶入式①和式②,得d|(c1+c2),且d|(c1-c2).(設為式③和式④)
聯立,得c1=c2,所以d|(2*c1),所以d肯定能被2整除。
證畢。
所以我們要通過操作把所有的數字都變成偶數。然后就貪心搞一搞就好了,記錄一下有多少個連續的奇數。
因為你會發現
對于兩個偶數來說,不需要操作,
對于兩個奇數,通過一次操作即可。
對于一奇一偶,通過兩次操作即可。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int n,a[MAX],g,cnt,ans; int main() {cin>>n;for(int i = 1; i<=n; i++) cin>>a[i],g=__gcd(a[i],g);puts("YES");if(g==1) {for(int i = 1; i<=n; i++) {if(a[i]%2==1) cnt++;else {ans += cnt/2+(cnt%2==1?2:0);cnt=0;} }ans += cnt/2+(cnt%2==1?2:0);}printf("%d\n",ans);return 0 ; }?
總結
以上是生活随笔為你收集整理的【Codeforces - 798C】 Mike and gcd problem(思维,贪心)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 申请信用卡初审通过 面签是最后一道坎
- 下一篇: 美国三季度GDP修正了,经济大增33.4