#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cmath>
#include<string.h>
#include<set>
#include<map>
#define LL long long
#define pr pair<int,int>
#define fr first
#define sc second
//#define mp make_pair
using namespace std;
LL read( ){LL sum=0;char c=getchar( );bool f=0;while(c<'0' || c>'9') {if(c=='-') f=1;c=getchar( );}while(c>='0' && c<='9') {sum=sum*10+c-'0';c=getchar( );}if(f) return -sum;return sum;}
void read(int &sum){sum=0;char c=getchar( );bool f=0;while(c<'0' || c>'9') {if(c=='-') f=1;c=getchar( );}while(c>='0' && c<='9') {sum=sum*10+c-'0';c=getchar( );}if(f) sum=-sum;}
void read(LL &sum){sum=0;char c=getchar( );bool f=0;while(c<'0' || c>'9') {if(c=='-') f=1;c=getchar( );}while(c>='0' && c<='9') {sum=sum*10+c-'0';c=getchar( );}if(f) sum=-sum;}
const int N=500005;
int n,a[N],b[N],p[N];
int gcd(int x,int y) {return y?gcd(y, x%y):x;}
int main( )
{
int i,x,y,L,R,T=read( );
while(T--)
{
read(n);
for(i=1;i<=n;i++) read(a[i]);
int cnt=0, ans=0;
for(i=1;i<=n;i++)
{
x=i;
y=(x==n?1:x+1);
if(a[x]!=a[y]) p[++cnt]=x;
}
while(cnt)
{
for(i=1;i<=cnt;i++)
{
x=p[i];
y=(x==n?1:x+1);
b[x]=gcd(a[x],a[y]);
}
set<int>S;
for(i=1;i<=cnt;i++)
{
x=p[i];
a[x]=b[x];
}
for(i=1;i<=cnt;i++)
{
x=p[i];
R=(x==n?1:x+1);
L=(x==1?n:x-1);
if(a[x]!=a[R] && a[x]!=1) S.insert(x);
if(a[L]!=a[x] && a[L]!=1) S.insert(L);
}
ans++;cnt=0;
for(auto &x:S) p[++cnt]=x;
if(!cnt) break;
}
printf("%d\n",ans);
}
return 0;
}
Nice solution :)
Can you/someone please help to elaborate this? I'm quite fascinated by this solution. I tried doing Brute Force for this problem submission:121999001 which got TLE. I did not find any way to optimize it which is mentioned in this post. It would be really nice if I could get any additional help in understanding the solution.
You check all elements in every round of BruteForce. There can be $$$N$$$ rounds , so it has a $$$O(N^2)$$$ complexity, may lead to TLE.
We can see that elements will change in the next round, are only in the elements change in this round and their left element, so we just check them.
Can you explain this sentence again?
For example, if $$$N=10$$$, and $$$a_3,a_7$$$ change in this round, then we can assert that only $$$a_2,a_3,a_6,a_7$$$ may change in the next round. We can only check whether $$$a_2,a_3,a_6,a_7$$$ will change in the next round. Other elements certainly won't change in the next round so we don't check them.
That's because: $$$a_i$$$ will change if $$$gcd(a_i, a_{i+1})\neq a_i$$$, so if both $$$a_i$$$ and $$$a_{i+1}$$$ does not change in this round, then $$$a_i$$$ won't change in the next round.
With the $$$\LaTeX$$$ markup, this looks like you're talking about factorials on first glance. You may want to consider instead writing this as: $$$x \neq y$$$. (Code is
x \neq y).Thanks! I've learned and fixed it.