[英]How do i reduce time complexity when using two nested while loops?
first input will be number of test cases t
, then given two numbers a
and b
you have to perform i
operations such that,第一个输入将是测试用例的数量
t
,然后给定两个数字a
和b
你必须执行i
操作,这样,
a
if i
is oddi
是奇数,则a
加 1a
if i
is eveni
是偶数,则将 2 添加到a
now print YES if a
can become equal to b
and NO if it can't现在如果
a
可以等于b
,则打印 YES,如果不能,则打印 NO
when I tried to submit my solution i
got error that time limit is exceeded.当我尝试提交我的解决方案时,
i
收到超过时间限制的错误。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t, a, b;
cin >> t;
while (t)
{
cin >> a >> b;
int flag = 1;
while (a != b && a < b)
{
if (flag % 2 == 0)
{
a += 2;
}
else
{
a += 1;
}
flag++;
}
if (a == b)
cout << "YES" << endl;
else
cout << "NO" << endl;
t--;
}
return 0;
}
You don't need to actually iterate from a
to b
, just use the following observations to solve:您不需要实际从
a
迭代到b
,只需使用以下观察来解决:
a
increases by 3
.a
的值增加了3
。 So after an even number of operations (let number be 2k
), a
increases by 3k
.2k
), a
增加了3k
。2k+1
), a
increases by 3k+1
.2k+1
), a
增加3k+1
。 As you can see, a
can either be increased by 3k
or 3k+1
, which implies that b
will be reachable from a
if (ba) mod 3 = (0 or 1)
(and obviously, if b>a
).如您所见,
a
可以增加3k
或3k+1
,这意味着b
可以从a
if (ba) mod 3 = (0 or 1)
到达(显然,如果b>a
)。 You can check this in O(1)
complexity.您可以在
O(1)
复杂度中检查这一点。
The inner loop can be simplified into a math expression.内部循环可以简化为数学表达式。 We can come up with the model using some examples.
我们可以通过一些例子来建立模型。
For example, if a = 10, b = 20.例如,如果 a = 10,则 b = 20。
Loop 1 a += 1 (11)
Loop 2 a += 2 (13)
Loop 3 a += 1 (14)
Loop 4 a += 2 (16)
...
We can see that after two operations, a increases by 3. Which can be generalized, that after the 2n operation (which represents an even number), that a increases by 3n.我们可以看到,经过两次操作后,a 增加了 3。可以概括为,经过 2n 次操作(表示偶数)后,a 增加了 3n。 On the other hand after the 2n + 1 operation (odd numbers), a is equal to an increase of 3n + 1. Thus, a can be increased either by 3n or 3n+1.
另一方面,在 2n + 1 运算(奇数)之后,a 等于增加 3n + 1。因此,a 可以增加 3n 或 3n+1。 Thus, 3n or 3n+1 has to be able to be equal to the difference of a and b, which in this case is 10.
因此,3n 或 3n+1 必须能够等于 a 和 b 的差,在本例中为 10。
Thus either因此,要么
1. 3 has to divide b - a, (b-a)%3 = 0
2. 3 has to divide b - a with a remainder of 1, (b-a)%3=1
Thus, instead of a loop, using a mathematical expression can simply the runtime to O(1) per input.因此,使用数学表达式代替循环可以简单地将每个输入的运行时间降低到 O(1)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.