清除竞争算法的测试用例

时间:2014-08-07 17:54:16

标签: c algorithm sorting testcase

我一直在为一个简单的算法清除所有测试用例,我正在寻找我应该在我的代码中做的原因或修改。 Here,该问题有内联链接。

可能的解决方案是对两个数组进行排序,然后添加相应的术语,但不能完成所有测试用例。

#include <stdio.h>
#include <assert.h>
int main() {
    long long n, i;

    scanf("%lld", &n);
    if (!(n >= 1 && n <= 1000000))
        exit(1);

    long long s[n], c[n], sum = 0, temp = 0, j;

    // taking input for cat and strength array
    for (i = 0; i < n; i++) {
        scanf("%lld", &s[i]);

        if (!(s[i] >= 1 && s[i] <= 1000000))
            exit(1);
    }
    for (i = 0; i < n; i++) {
        scanf("%lld", &c[i]);
        if (!(c[i] >= 1 && c[i] <= 1000000))
            exit(1);
    }

    // Sorting the C array
    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (c[i] > c[j]) {
                temp = c[i];
                c[i] = c[j];
                c[j] = temp;
            }
        }
    }

    // sorting the S array
    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (s[i] > s[j]) {
                temp = s[i];
                s[i] = s[j];
                s[j] = temp;
            }
        }
    }

    // Finally adding up the sorted elements
    for (i = 0; i < n; i++) {
        sum = sum + (s[i] * c[i]);
    }

    printf("%d ", sum);
    getch();
}

2 个答案:

答案 0 :(得分:1)

  1. 要避免运行时错误,请在全局范围内声明大小(1e6)的数组。
  2. 为避免超出时间限制,请注意您使用的排序需要O(N ^ 2)时间,因此对于大小为1e6的数组,在最坏的情况下排序最多需要1e12(近似)计算操作。标准排序算法(合并排序,快速排序)需要O(NlgN)时间,这比当前方法好得多,而c[i], s[i] <= 1e6甚至可以在线性时间内对数组进行排序。
  3. 哦,为了克服Wrong answers,将printf("%d ",sum);替换为printf("%lld ",sum); sum是long long type的变量

答案 1 :(得分:0)

请注意n <= 10^6。您的算法具有O(n^2)时间复杂度。太慢了。你肯定需要使用更有效的排序算法。例如,您可以使用qsort中的stdlib.h

相关问题