简体   繁体   English

清除竞争算法的测试案例

[英]Clearing Test Cases of a competitive alogithm

I am stuck in clearing all the test cases for a simple algorithm and I am looking for the reasons or the modifications that I should be doing in my code. 我一直致力于清除所有测试用例的简单算法,并且正在寻找原因或应在代码中进行的修改。 Here , there is an inline link to the question. 在这里 ,有一个到该问题的内联链接。

The probable solution can be sorting the two arrays and then adding the corresponding terms but it does not complete all the test cases. 可能的解决方案是对两个数组进行排序,然后添加相应的术语,但它不能完成所有测试用例。

#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();
}
  1. To avoid runtime error, declare the arrays with large size(1e6) in global scope. 为避免运行时错误,请在全局范围内声明具有大尺寸(1e6)的数组。
  2. To avoid Time Limit Exceeded, please note that the sorting you are using takes O(N^2) time, so for an array with size 1e6, the sorting takes upto 1e12(approx) computational operations in the worst case. 为避免超过“时间限制”,请注意,您使用的排序需要O(N ^ 2)时间,因此对于大小为1e6的数组,在最坏的情况下,排序最多需要1e12(大约)个计算操作。 Standard sorting algorithms(merge sort, quick sort) take O(NlgN) time which is much better than the current approach and as c[i], s[i] <= 1e6 you can even sort the arrays in linear time. 标准排序算法(合并排序,快速排序)占用的时间为O(NlgN),这比当前方法要好得多,并且由于c[i], s[i] <= 1e6您甚至可以线性时间对数组进行排序。
  3. Oh, and to overcome Wrong answers , replace printf("%d ",sum); 哦,要克服Wrong answers ,请替换printf("%d ",sum); with printf("%lld ",sum); printf("%lld ",sum); sum is a variable of long long type sum是long long类型的变量

Note that n <= 10^6 . 注意n <= 10^6 Your algorithm has O(n^2) time complexity. 您的算法的时间复杂度为O(n^2) It is too slow. 太慢了。 You definitely need to use more efficient sorting algorithm. 您肯定需要使用更有效的排序算法。 For example, you can use qsort from stdlib.h . 例如,您可以使用stdlib.h qsort

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

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