Mike and gcd problem CodeForces, gcdcodeforces
Question
(IQ questions or bad greed)
Question:
There is a series a1, a2 ,..., an, each operation can change the adjacent two numbers x and y to x-y, x + y, and obtain the least operand so that gcd (a1, a2 ,..., an)> 1. Gcd (a1,..., an) indicates the largest non-negative integer so that all ai can be divisible by gcd (a1,...,.
Analysis:
First, if the original gcd is not 1, then the answer is 0.
If gcd is 1:
The change of adjacent two numbers x and y is as follows: x, y => x-y, x + y
If a new gcd value is set to d, x-y and x + y can be divisible by d, so 2x and 2y can be divisible by d,
Therefore, d is twice the maximum gcd of x and y.
Therefore, you only need to consider how to change all numbers to an even number (the number must be the smallest)
X odd y even
=> X odd y odd
X even y odd
=> X odd y odd
X even y even
=> X even y even
X odd y odd
=> X even y even
Mark an even number as 0, an odd number as 1,
Then it becomes an xor operation.
The entire question becomes a given series composed of 0/1. Each time two adjacent numbers can be changed to their different or result,
Finally, convert all numbers to 0.
In this way, it is easy to come up with greedy practices. If k consecutive 1:
If k is an even number, k/2 operations are required to change to 0.
If k is an odd number, then the [k/2] operation is required to change the K-1 to all 0, and then the next and next 0
(Because the previous [k/2] operation produces 0, there must be 0 next to that one) the result of two operations is 0.
1 #include<cstdio> 2 int d,n,ans; 3 int a[110000],b[110000],num_b; 4 int gcd(int a,int b) 5 { 6 int t; 7 while(b!=0) 8 { 9 t=a;10 a=b;11 b=t%b;12 }13 return a;14 }15 int main()16 {17 int i;18 scanf("%d",&n);19 for(i=1;i<=n;i++)20 {21 scanf("%d",&a[i]);22 d=gcd(d,a[i]);23 a[i]%=2;24 }25 printf("YES\n");26 if(d!=1)27 {28 printf("0\n");29 return 0;30 }31 if(a[1]==1)32 b[++num_b]++;33 for(i=2;i<=n;i++)34 {35 if(a[i]==1&&a[i-1]==0)36 b[++num_b]++;37 else if(a[i]==1)38 b[num_b]++;39 }40 for(i=1;i<=num_b;i++)41 {42 if(b[i]%2==0)43 ans+=b[i]/2;44 else45 ans+=b[i]/2+2;46 }47 printf("%d\n",ans);48 return 0;49 }