CodeForces798cMike 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 A beautiful 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.
Example
Input 21 1 Output YES
1 Input 3
6 2 4 Output YES
0 Input 2
1 3 Output 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.
第一行一個n,代表n個數字輸入,第二行輸入數字,你可以對第i個數和第i+1執行一種交換操作,即用ai,?ai?+?1?替代ai?-?ai?+?1,?ai?+?ai?+?1
求最少進行多少次操作,能使該序列的最大公共公因數>1,這里題目是絕對有解的,不需考慮no的情況
對于數字a,b進行操作:? a,b ? a-b,a+b? -2b,2a
由此題目就容易了,2是最容易想到的最大公因數,而進行操作又可以令無論奇偶的兩個數都變成偶數
那么對數組進行訪問
1.假如第i個數和第i+1個數都為偶數,操作次數為0(不產生影響,不用判斷)
2.假如第i個數和第i+1個數都為奇數,操作次數為1
3.假如一個奇數一個偶數,操作次數為2
但這里就有一個問題了,2和3之間存在沖突,并且2幾乎無法觸發。而題目求的是最少操作數量,那么顯然2是優于3的,所以在處理時應給2更高的優先級。因此可以對數組進行兩次訪問,第一次執行操作2,第二次執行操作3。
另外,題目有一個要注意的地方是在交換前最大公共公因數已經符合條件的話,可以直接結束,代碼如下
#include<stdio.h> #define MAX 100000 int gcd(int s1,int s2) {int r;while (s2!=0) {r=s1%s2;s1=s2;s2=r;}return s1; } int main() {int n,i,j,a[MAX],t,ans;while(scanf("%d",&n)!=EOF){t=0;for(i=1;i<=n;i++){scanf("%d",&a[i]);}ans=gcd(a[1],a[2]);for(i=3;i<=n;i++)ans=gcd(ans,a[i]);if(ans>1)printf("YES\n0\n");else{?ans=0;for(i=2;i<=n;i++){if(a[i-1]%2&&a[i]%2){ans++;a[i-1]=0;a[i]=0;}}for(i=2;i<=n;i++){if(a[i-1]%2==0&&a[i]%2||a[i-1]%2&&a[i]%2==0){ans+=2;a[i-1]=0;a[i]=0;}}printf("YES\n%d\n",ans);}} }?
轉載于:https://www.cnblogs.com/qq936584671/p/6814876.html
總結
以上是生活随笔為你收集整理的CodeForces798cMike and gcd problem的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 素材
- 下一篇: Andorid ListView使用技巧