2017-04-04 65 views
1

我一直在爲它掙扎2天。請問誰能告訴我爲什麼超過時間限制,當我用作輸入20000以及0和40000之後的數字?我試圖讓變量類型儘可能大,但這似乎也沒有幫助。誰能告訴我爲什麼這會超過2秒的時間限制?(短代碼)

#include <bits/stdc++.h> 

using namespace std; 

int main() 
{ 
    /*freopen("file.in", "r", stdin); 
    freopen("file.out", "w" , stdout);*/ 
    long long int aux,i, n, k, j, total = 0; 
    cin >> n >> k; 
    long long int a[n], b[n], order[n]; 
    signed long long int profit[n]; 
    for(i = 0; i < n; i++) 
     cin >> a[i]; 
    for(i = 0; i < n; i++) 
     cin >> b[i]; 
    for(i = 0; i < n; i++) 
     profit[i] = a[i] - b[i]; 
    for(i = 0; i < n; i++) 
     order[i] = i; 
    for(i = 0; i < n; i++) 
     for(j = i + 1; j < n; j++) 
      if(profit[order[i]] > profit[order[j]]) 
      { 
       aux = order[i]; 
       order[i] = order[j]; 
       order[j] = aux; 
      } 
    if(k > 0) 
     for(i = 0; i < k; i++) 
     { 
      total += a[order[i]]; 
     } 

    for(i = k; i < n; i++) 
    { 
     if(profit[order[i]] < 0) 
      total += a[order[i]]; 
     else 
      total += b[order[i]]; 
    } 
    cout << total; 

    return 0; 
} 
+0

你是否分析了你的代碼,以確定它實際上花在哪裏? –

+0

我該怎麼做? –

+0

你可以從這裏開始閱讀:http://stackoverflow.com/questions/2229336/linux-application-profiling和'#include '?!?!?不就是不。不要那樣做。見http://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h?noredirect=1&lq=1 –

回答

1

你的代碼的複雜度是O(n^2),這對於N = 20000來說太多了。降低複雜性,用Qsort替換你的氣泡排序。試用std::sort自定義比較功能。

+0

如何使用std:sort?我不熟悉它。 並且quicksort也沒有表現O(n^2)的最壞情況scenerio? –

+0

這取決於實施。當你選擇帶有O(n log n)的隨機樞軸元素時。如果你想要的話,你可以使用合併排序或複雜度爲O(log n) –

相關問題