In this question, we can dispart the sequence, then you will obtain $$$n$$$ pairs of $$$a_i$$$ and $$$b_i$$$. To judge whether the answer is YES
or NO
, we can compare the steps of making $$$a_i$$$ equals to $$$0$$$. Let the steps to be $$$k_1, k_2, \dots, k_{n-1}, k_n$$$, if $$$k_1\equiv k_2\equiv \dots \equiv k_{n - 1}\equiv k_n\pmod{3}$$$, then the answer is YES
, otherwise it's NO
. The reason is when $$$a_i = 0, b_i = y$$$, then after two more operations, it will be $$$a_i = 0, b_i = y$$$ again and the state of these two operations are $$$a_i = y, b_i = y$$$ and $$$a_i = y, b_i = 0$$$, so it's a cycle with a period of three.
Then, the main problem is how to calculate the value of $$$k_i\bmod 3$$$. The most violent way is to do it step by step, however it will be $$$\color{red}{Time\enspace limit\enspace exceed}$$$. Accordingly, this way is not desirable. Now, let $$$x = a_i$$$ and $$$y = b_i$$$, if $$$y > x$$$, then after $$$3$$$ operations, $$$b_i$$$ will equals to $$$y - 2x$$$, and after $$$6$$$ operations, $$$b_i$$$ will equals to $$$y - 4x$$$, and so on. Accordingly, we can let $$$y = y \bmod 2x$$$ and because of the period is $$$3$$$, then it won't change the value of $$$k_i \bmod 3$$$. Otherwise, we just do the violent operation. The time complexity will be about $$$O(n\log n)$$$ on account of the modulo operation. It will be much faster than before!
#include <iostream>
#include <tuple>
using namespace std;
const int N = 1e5 + 10;
int Data;
int n;
int a[N], b[N];
int main()
{
scanf("%d", &Data);
while (Data --)
{
scanf("%d", &n);
for (int i = 1; i <= n; i ++)
scanf("%d", &a[i]);
for (int i = 1; i <= n; i ++)
scanf("%d", &b[i]);
int t = -1, flg = 1;
for (int i = 1; i <= n; i ++)
{
if (a[i] == b[i] && a[i] == 0) continue; //If a[i] and b[i] are all zero, it won't affect the answer.
int x = a[i], y = b[i], v = 0;
while (x != 0)
{
y %= (2 * x); //Use a more fater way
tie(x, y) = make_pair(y, abs(x - y)); //the violent way
v = (v + 1) % 3; //Because of the violent way, we need to increase 1 step.
}
if (t != -1 && v != t) //This means there will be two k[i] that are dissimilar in the sense of modulo 3
{
puts("NO");
flg = 0;
break;
}
t = v;
}
if (flg) puts("YES");
}
}
This is clearer than the tutorial. Thx.
Thanks for this!
Better than the editorial's one
Thank you for your support.