【问题标题】:Fastest way to find if a lot numbers are in multiple intervals查找批号是否在多个间隔中的最快方法
【发布时间】: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,然后从那里继续。或者去学校/学院/大学。实际上,包括&lt;bits/stdc++.h&gt; 将包含比您可能需要的更多的头文件,从而使您的代码编译大大更慢
  • 提示:1. 对数字进行排序 2. 使用std::lower_bound
  • 您的问题非常适合“分治算法”

标签: c++ algorithm sorting


【解决方案1】:

正如 DAle 已经指出的那样。

您可以先对 n 个数字进行排序。一个好的算法,比如合并或堆排序,会给你一个复杂度 O(n*log(n))。

之后,您需要对每个间隔的“第一”和“第二”部分使用搜索算法。根据算法,复杂度应该在 O(log(n)) 左右 - std::lower_bound 在处理排序数据时具有 O(log(n)) 的复杂度,所以它已经足够好了。或者所有时间间隔都是 O(m*log(n))。

比较搜索结果将为您提供每个区间内的数字数量。

总共大约有 O((m+n)*log(n))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-06
    • 2017-06-08
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2013-03-04
    相关资源
    最近更新 更多