Detailed explanation#C. gcd of multiple numbers

topic


Idea 1

It is to directly simulate the meaning of the question, enumerate the changed number and change it, calculate their greatest common divisor , and take the maximum value .

Time complexity: O(n * n * log(n)), will time out

Because it is too simple, the code of this idea is not given here.


Idea 2

This question requires preprocessing to reduce time complexity.

The idea is to traverse the array and store the result of gcd(a[1],a[2]...a[i]) in b[i] ,

Then traverse the array backwards and store the result of gcd(a[n],a[n - 1]...a[n - i + 1]) in c[n - i + 1]

Then enumerate the number a[i] to be changed , and take gcd(b[i - 1], c[i + 1]) for ans.

Principle: Because the gcd results of several numbers must be <= the minimum value among them, the number changed from a[i] to >b[i - 1], c[i + 1] and their multiples is optimal, Then the number changed to a[i] in gcd (the number changed by a[i], b[i - 1], c[i + 1]) has no effect on the result, so take gcd(b [ i - 1], c[i + 1]


the code

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,a[10000001],b[10000001],c[10000001],s,ans;
signed main()
{
  cin>>n;
  for(int i = 1;i <= n;i++) cin>>a[i];
  for(int i = 1;i <= n;i++)
  {
      s = __gcd(s,a[i]);
      b[i] = s;
  }
  s = 0;
  for(int i = n;i > 0;i--)
  {
      s = __gcd(s,a[i]);
      c[i] = s;
  }
  for(int i = 1;i <= n;i++)
  {
      int ta = b[i - 1],tb = c[i + 1],tc = __gcd(ta,tb);
      ans = max(ans,tc);
  }
  cout<<ans;
  return 0;
}

Guess you like

Origin blog.csdn.net/weq2011/article/details/128773383