簡體   English   中英

清除競爭算法的測試案例

[英]Clearing Test Cases of a competitive alogithm

我一直致力於清除所有測試用例的簡單算法,並且正在尋找原因或應在代碼中進行的修改。 在這里 ,有一個到該問題的內聯鏈接。

可能的解決方案是對兩個數組進行排序,然后添加相應的術語,但它不能完成所有測試用例。

#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. 為避免運行時錯誤,請在全局范圍內聲明具有大尺寸(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類型的變量

注意n <= 10^6 您的算法的時間復雜度為O(n^2) 太慢了。 您肯定需要使用更有效的排序算法。 例如,您可以使用stdlib.h qsort

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM