简体   繁体   English

如何进一步优化这个简单的算法?

[英]How to optimize this simple algorithm further?

Note: this is a programming challenge 注意:这是编程挑战


This challenge requires usage of std::set . 这个挑战需要使用std::set

Input 输入

  • A number n 数字n
  • n lines with each j and k 每行jkn

Sample input: 样本输入:

 5 1 4 2 1 1 6 3 4 1 2 

j is for the operation: 1 to insert k , 2 to delete k (if there is a k ), 3 find k j用于操作: 1插入k2插入删除k (如果有k ), 3k

For j == 3 , output Yes or No if k is in the std::set . 对于j == 3 ,如果kstd::set ,则输出YesNo


I made different versions of the algorithm, but all are way too slow. 我做了不同版本的算法,但都太慢了。 I tried different std functions, but std::find seems the fastest one, but is still too slow. 我尝试了不同的std函数,但std::find似乎是最快的,但仍然太慢了。 Implementing my own would be even worse, so maybe I missed a function from the library. 实现我自己会更糟,所以也许我错过了图书馆的功能。 I really have no idea how to optimize it further. 我真的不知道如何进一步优化它。 Currently I have this: 目前我有这个:

 int main() { std::set<int> set{}; int Q = 0; std::cin >> Q; int type = 0; int x = 0; for (int i = 0; i < Q; ++i) { std::cin >> type; std::cin >> x; if (type == 1) set.insert(x); else if (type == 2) set.erase(x); else if (type == 3) std::cout << (std::find(std::begin(set), std::end(set), x) != std::end(set) ? "Yes" : "No") << '\\n'; //Condition may be std::find, std::count or std::binary_search } return 0; } 


The challenge requires it to run under 2 seconds. 挑战要求它在2秒内运行。 Here are the results of mine: 以下是我的结果:

 Function Time % over std::find -> 7.410s 370.50% std::count -> 7.881s 394.05% std::binary_search -> 14.050s 702.50% 

As you can see my algorithm is 3x slower than the required algorithm. 如您所见,我的算法比所需算法慢3倍。 The bottlenecks are clearly those functions: 瓶颈显然是那些功能:

 Function % of total time std::find -> 77.61% std::count -> 80.80% std::binary_search -> 87.59% 

But currently I have no better idea than to use std::find or similar functions. 但目前我没有比使用std::find或类似函数更好的想法。 Does someone have a way/idea to optimize my code further? 有人有办法/想法进一步优化我的代码吗? Or are there some obvious bottlenecks that I'm missing? 还是有一些我不知道的明显瓶颈?

You want to use set.find() and not std::find(set.begin(),set.end()) . 你想使用set.find()而不是std::find(set.begin(),set.end())

set.find() will use the set's internal structure to locate the key in O(log(n)) time. set.find()将使用set的内部结构在O(log(n))时间内定位键。 Whereas std::find is a linear search, requiring O(n) time, no matter what container type is used. std::find是线性搜索,无论使用何种容器类型,都需要O(n)时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM