【发布时间】:2018-06-14 04:31:12
【问题描述】:
所以我有一个任务。我得到了 n 个数字和 m 个间隔,我需要弄清楚第 i 个间隔中有多少个数字。我编写了一些复杂度为 O(n*m) 的代码,但我需要对其进行更多优化。有什么帮助吗? 代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
cout.tie(0);
int n,m,temp,temp1;
vector <pair<int, int>> uogienes;
vector <int> erskeciai;
cin >> n >> m;
for (int i = 0; i< n; i++){
cin>>temp;
erskeciai.push_back(temp);
}
temp = 0;
for (int i = 0; i<m; i++){
cin>> temp >> temp1;
uogienes.push_back(make_pair(temp, temp1));
}
for(int i = 0; i<m; i++){
temp=0;
for(int h = 0; h<n; h++){
if(uogienes[i].first <= erskeciai[h] && uogienes[i].second >= erskeciai[h]){
temp++;
}
}
cout << temp << "\n";
}
return 0;
}
【问题讨论】:
-
您的代码有效吗?如果确实如此,并且您想要的只是有关可能优化的提示,那么您应该改为在codereview.stackexchange.com 上发帖。但首先请阅读Why should I not #include <bits/stdc++.h>? 和Why is “using namespace std” considered bad practice?
-
是的,它确实有效,只是错误地插入了代码,因为我在移动设备上。我只使用它们,因为我是一个有竞争力的程序员,所以时间很宝贵。 @一些
-
做“竞争性”编程只会教你竞争性编程。如果你真的想学习如何编程 C++ get a good beginners book or two,然后从那里继续。或者去学校/学院/大学。实际上,包括
<bits/stdc++.h>将包含比您可能需要的更多的头文件,从而使您的代码编译大大更慢! -
提示:1. 对数字进行排序 2. 使用
std::lower_bound -
您的问题非常适合“分治算法”