【问题标题】:Linear vector search too slow for online judge线性向量搜索太慢,无法在线判断
【发布时间】:2021-01-22 05:11:14
【问题描述】:

问题陈述:我们必须输入一个向量,然后有一定数量的查询。对于一个特定的查询,我们必须在向量中搜索该数字。如果找到,我们打印。“是”,如果没有找到,我们将下一个更大的数字打印到查询并打印“否”。 向量已排序。

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int size,q,nq=0;
    cin>>size;
    vector<int> vec1;
    int element;
    for (int i = 0; i < size; i++)
    {
        cin>>element;
        vec1.push_back(element);
    }
    cin>>q;
    for(int j=0;j<q;j++)
    {
        cin>>nq;
        for(int k=0;k<vec1.size();k++)
        {
            if(vec1[k]==nq)
            {
                cout<<"Yes "<<k+1<<endl;
                break;
            }
            else if(vec1[k]>nq)
            {
                cout<<"No "<<k+1<<endl;
                break;
            }
        }
    }     
    return 0;
}

代码运行完美,但对于某些测试用例,由于时间原因出现错误。 我需要改进这段代码。我正在为此苦苦挣扎,因为我刚刚了解了 std::vector。

【问题讨论】:

  • 如果向量已排序,binary search 是 O(log(n)),而线性搜索是 O(n)。它应该大大加快研究速度。
  • 在解决编程竞赛类型的问题时,请始终查看问题陈述中的大小限制。简单而幼稚的方法很少足够快,但通常是与完全不同的实现进行比较的良好基准。
  • 无论时间限制如何(如前所述,您应该在哪里使用 binary_search),您的代码似乎并没有按要求执行。如果找到数字,则打印“是”和向量中的下一个数字,但如果我理解正确,您应该只在“否”的情况下打印下一个数字。

标签: c++ vector stl


【解决方案1】:

由于这个问题与排序向量有关,因此需要使用二分搜索。 二进制搜索允许以 O(Log(N))O(N) 复杂度 (https://en.wikipedia.org/wiki/Computational_complexity) 回答查询。所以这就是为什么你的实现对于这个问题来说太慢了。

这里是手动实现Using Binary Search with Vectors. 而且使用std::lower_bound函数也更清楚了。它确实是需要的东西:

#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

    int main() {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
        int size,q,nq=0;
        cin>>size;
        vector<int> vec1;
        int element;
    
        for (int i = 0; i < size; i++)
        {
            cin>>element;
            vec1.push_back(element);
        }
        cin>>q;
    
        vector<int>::iterator qit;
    
        for(int j=0;j<q;j++)
        {
            cin>>nq;
    
            qit = std::lower_bound(vec1.begin(), vec1.end(), nq);
    
            if(qit != vec1.end())
            {
                if(*qit == nq)
                    cout << "Yes " << (qit - vec1.begin());
                else cout << "No " << *qit << " " << (qit - vec1.begin());
            }
            else cout << "No " << (qit - vec1.begin());
        }     
        return 0;
    }

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    相关资源
    最近更新 更多