gpt4 book ai didi

c++ - 谁能告诉我为什么这超过了 2 秒的时间限制?(短代码)

转载 作者:行者123 更新时间:2023-11-30 05:15:12 25 4
gpt4 key购买 nike

我已经苦苦挣扎了2天。拜托,有人能告诉我为什么当我之后输入20000和0和40000数字时它超过了时间限制吗?我试图使变量类型尽可能大,但这似乎也无济于事。

#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;
}

最佳答案

您的代码复杂度为 O(n^2),对于 N=20000 来说太多了。降低复杂性,用 Qsort 代替冒泡排序。尝试使用自定义比较函数的 std::sort

关于c++ - 谁能告诉我为什么这超过了 2 秒的时间限制?(短代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43207486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com