【问题标题】:Possible Path [Hackerrank] compilation timeout可能的路径 [Hackerrank] 编译超时
【发布时间】:2016-07-09 23:59:24
【问题描述】:

我已经在另一个编译器上尝试了我的代码,并且所有测试用例都能正常工作。不幸的是,hackerrank 的编译器超时。任何人都可以提出一些建议以使我的代码更高效。

问题: Adam 站在无限二维网格中的 (a,b) 点。他想知道他是否可以到达点 (x,y)。他唯一能做的操作是从某个点 (a,b) 移动到点 (a+b,b)、(a,a+b)、(a-b,b) 或 (a,a-b)。假设他可以移动到这个 2D 网格上的任何点,即具有正或负 X(或 Y)坐标的点。

告诉亚当他是否可以到达 (x,y)。

我的代码:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>

long int GreatestCommonDivisor(long int a, long int b)
{
    long int div = 1;
    long int res;

    while ( div <= a)
    {
        if ((a % div == 0) && (b % div == 0)) res = div;
        div++;
    }
    return res;
}

int main() {
    int n, i;
    scanf("%d", &n);

    for (i = 0; i < n; i++)
    {
        long int a, b, x, y;
        scanf("%ld %ld %ld %ld", &a, &b, &x, &y);

        long int p1 = GreatestCommonDivisor(a, b);
        long int p2 = GreatestCommonDivisor(x ,y);

        if ( p1 == p2) printf("YES\n");
        else printf("NO\n");

    }
    return 0;
}

【问题讨论】:

  • 如果您的代码按需要编译并且您想要进行批判性分析,请在代码审查网站上发布您的问题
  • 如果真的是编译器而不是你的程序超时了,可能是服务器的问题。您应该使用欧几里得算法来使您的程序更快。
  • 不,这是你的工作,在挑战网站上。这就是重点,不仅要提交一个可行的简单解决方案,还要提交一个行之有效的尖锐解决方案。
  • 让别人解决你的挑战问题是作弊。
  • 不,你还没有解决。如果你有,你会得到正确的答案。据我们所知,实际测试可能会在时间限制内给出错误答案。正如我所说,真正的问题是找到一个巧妙的解决方案。

标签: c path timeout


【解决方案1】:

你需要一个更高效的算法:

#include <stdio.h>
#include <stdbool.h>

long int greatestCommonDivisor(long int m, long int n) {
    long int r;

    /* Check For Proper Input */
    if ((m == 0) || (n == 0))
        return 0;
    else if ((m < 0) || (n < 0))
        return -1;

    do {
        r = m % n;
        if (r == 0)
            break;
        m = n;
        n = r;
    }
    while (true);

    return n;
}

char *array[12];

int main() {
    int n, i;
    scanf("%d", &n);

    for (i = 0; i < n; i++) {
        long int a, b, x, y;
        scanf("%ld %ld %ld %ld", &a, &b, &x, &y);

        long int p1 = greatestCommonDivisor(a, b);
        long int p2 = greatestCommonDivisor(x, y);

        if (p1 == p2) array[i] = ("YES\n");
        else array[i] = ("NO\n");

    }
    for (i = 0; i < n; i++) {
        printf("%s", array[i]);

    }
    return 0;
}

您的原始版本也没有通过输出测试,您必须对其进行格式化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 2021-02-05
    • 2011-12-15
    相关资源
    最近更新 更多