繁体   English   中英

当我尝试运行此代码时,出现时间限制超出错误,执行需要 1.01 毫秒

[英]When I try to run this code I am getting time limit exceeded error and it's taking 1.01 ms to execute

Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0) {
    int n=sc.nextInt();
    while(true) {
        boolean ok = true;
        int num = n;
        while(num > 0) {
            if(ok && num % 3 == 2)
            ok = false;
            num = num / 3;
        }
        if (ok)
            break;
        ++n;
    }
    System.out.println(n);        
}

如何优化我的代码? 此代码正在计算 integer,它可以表示为 3 的不同幂的总和。

您的代码在 $O(N \log N)$ 中运行。 我认为您正试图从 CodeForces 解决这个问题 您没有提到 $n$ 的限制,但问题是 $n$ 可以大到 $10^18$,$O(N \log N)$ 解决方案将完全失败。 而且题中提到可能有500个查询,你需要在时限内解决500次查询。

请注意,只要超过时间,您就会在那些竞争性节目网站上收到“超过时间限制”。 这并不意味着您的代码在 1.01 秒内执行,并且您仅错过了 0.01 秒的限制。 这只是意味着您的代码未能在 1 秒内执行并在 1.01 秒内停止。 如果允许运行,您无法理解您的代码需要多长时间。 您可以在自己的机器上进行这些检查。

说了所有这些,提示问题的解决方案:

观察:任何数字 $n$ 如果其 base-3 表示包含“2”,则不能表示为 3 的不同幂的总和。

然后,问题只是要求最小的 integer 大于或等于 n 并且在其 base-3 表示中不包含“2”。

考虑数字的 base-3 表示中最重要的“2”数字。 取“2”之前的数字。 计算包括“2”在内的“剩余”位数。 假设该数字以 2 为底,并添加“1”。 将“剩余”数量的尾随零数字添加到数字中。 将该“base-3”数字转换为 base-10,然后将 output 转换为结果。

该算法在 $O(log N)$ 中运行,这足以获得“答案正确”。

利用 Java BigInteger 的解决方案如下:

void solve(long n) {
    final char[] chars = BigInteger.valueOf(n).toString(3).toCharArray();

    final int twoDigit = getTwoDigit(chars);
    if (twoDigit == -1) {
        System.out.println(n);
    } else {
        int remaining = chars.length - twoDigit;

        final BigInteger a;
        if (twoDigit == 0) {
            a = BigInteger.ONE;
        } else {
            a = new BigInteger(new String(chars, 0, twoDigit), 2).add(BigInteger.ONE);
        }
        BigInteger b = new BigInteger(a.toString(2), 3);
        BigInteger result = b.multiply(BigInteger.valueOf(3).pow(remaining));
        System.out.println(result);
    }
}

private static int getTwoDigit(char[] chars) {
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] == '2') {
            return i;
        }
    }
    return -1;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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