简体   繁体   中英

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.
  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. 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.
  3. Oh, and to overcome Wrong answers , replace printf("%d ",sum); with printf("%lld ",sum); sum is a variable of long long type

Note that n <= 10^6 . Your algorithm has O(n^2) time complexity. It is too slow. You definitely need to use more efficient sorting algorithm. For example, you can use qsort from stdlib.h .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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