简体   繁体   English

使用两个嵌套的while循环时如何降低时间复杂度?

[英]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 ,然后给定两个数字ab你必须执行i操作,这样,

  • add 1 to a if i is odd如果i是奇数,则a加 1
  • add 2 to a if i is even如果i是偶数,则将 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 ,只需使用以下观察来解决:

  • After 2 operations, the value of a increases by 3 .经过 2 次操作后, a的值增加了3 So after an even number of operations (let number be 2k ), a increases by 3k .因此,经过偶数次操作(让数字为2k ), a增加了3k
  • Similarly, for an odd number of operations (of form 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可以增加3k3k+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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM