码迷,mamicode.com
首页 > 其他好文 > 详细

G - Mike and gcd problem

时间:2017-05-05 23:16:18      阅读:399      评论:0      收藏:0      [点我收藏+]

标签:enter   ant   ini   lib   sample   form   length   nts   size   

G - 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?+?1in 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 sequenceA beautiful.

Example

Input
2
1 1
Output
YES
1
Input
3
6 2 4
Output
YES
0
Input
2
1 3
Output
YES
1
题意:输入n个数 (2?≤?n?≤?100?000),操作:把a[i],a[i+1] 替换成 a[i]-a[i+1],a[i]+a[i+1],问最少多少次操作
使所有元素的gcd>1。
题解:假设两个数a,b。操作一次a-b,a+b. 操作两次 -2b,2a。gcd=2;
所以任意两个数两次操作后gcd一定>1;
当两个数是偶数时,需要0次操作
当两个是奇数时,需要1次操作
当一奇一偶时,需要2次操作
先循环一遍两个都是奇数的,然后把这两个数更改为偶数,操作次数+1;
在循环一遍一奇一偶成对的,然后把这两个数更改为偶数,操作次数+2;
代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cstdio>
long long gcd(long long a,long long b)
{
    if(b==0)
        return a;
    else
        gcd(b,a%b);
}
using namespace std;
int main()
{
    long long a[100005],ans;
    int n,i,num=0;
    cin>>n;
    for(i=1;i<=n;i++)
        cin>>a[i];
    ans=gcd(a[1],a[2]);
    for(i=3;i<=n;i++)
        ans=gcd(ans,a[i]);
    if(ans>1)
        cout<<"YES"<<endl<<0<<endl;
    else
    {
        for(i=1;i<n;i++)
        {
            if(a[i]%2&&a[i+1]%2)
            {
                a[i]=0; a[i+1]=0; num++;
            }
        }
        for(i=1;i<n;i++)
        {
           if(a[i]%2==0&&a[i+1]%2==1)
           {
               a[i]=0; a[i+1]=0; num+=2;
           }
            else if(a[i]%2==1&&a[i+1]%2==0)
            {
                a[i]=0; a[i+1]=0; num+=2;
            }
            else
                continue;
        }
        cout<<"YES"<<endl<<num<<endl;
    }
}

 


 

G - Mike and gcd problem

标签:enter   ant   ini   lib   sample   form   length   nts   size   

原文地址:http://www.cnblogs.com/GXXX/p/6814992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!