1. 程式人生 > >code force 798cMike and gcd problem

code force 798cMike and gcd problem

sub while 並且 cati put ins i++ des 替代

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 a

i,?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
2
1 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);
  }
 }
}

code force 798cMike and gcd problem