【问题标题】:How to output the number of element that is between the given min and max in given vector如何输出给定向量中给定最小值和最大值之间的元素数
【发布时间】:2021-06-24 23:14:54
【问题描述】:

我在一些竞争性的编码网站上做了一些问题,它基本上要求你计算有多少元素大于最小值并且小于或等于最大值

例如,我有一个数组 {3,6,8,10,20},最小值为 2,最大值为 15,如果我将最小值更改为 10,则元素数为 4(从 3 到 10)并且最大到 20 元素的数量是 1 (20) 因为 20 等于最大值

这是我的代码

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    vector<int> bebek;
    std::vector<int>::iterator low1, up1;
    int N,Q, input, input2, ct;
    cin >> N;
    for (int i = 0; i < N; i++)
    {
        cin >> input;
        bebek.push_back(input);
    }
    cin >> Q;
    for (int i = 0; i < Q; i++)
    {
        cin >> input >> input2;
        low1 = lower_bound(bebek.begin(), bebek.end(), input+1);
        up1 = upper_bound(bebek.begin(), bebek.end(), input2-1);
        cout << distance(low1, up1) << endl;

        

    }
    
    
    return 0;
}

输入:
5(数组中元素的数量)
3 6 8 10 20(元素)
2(最小值和最大值)
2 15(最小和最大)
10 20(最小最大 2nd)

预期输出:
4
1

当前输出:
4
0

我可以做些什么来改进我的算法

【问题讨论】:

  • 输入是否保证排序?
  • 我认为这可以用二叉索引树(Fenwick 树)来解决。
  • @Meowmere 是的,网站是这么说的
  • @AndyG 你能在回答部分详细说明吗
  • BIT 允许对频率计数进行有效插入、更新和查询(均以对数时间计算)。如果您的查询与插入/更新交错,那么它是最优化的数据结构。否则,如果您已经提前拥有了所有元素,那么最简单的方法是对集合进行排序,然后使用二分搜索查找最小值和最大值的偏移量,以便执行频率计数。

标签: c++ lower-bound upperbound


【解决方案1】:

#include &lt;bits/stdc++.h&gt;
That is not a standard include file.

using namespace std;
Don't do that.

std::vector<int>::iterator low1, up1;
int N,Q, input, input2, ct;

不要像那样在顶部声明所有变量!
在需要的地方以及准备初始化的时候声明变量。
特别是,low1up1 在内部范围内使用。他们应该在那里声明,顺便说一句,使用auto。例如

const auto low1 = lower_bound(bebek.begin(), bebek.end(), input+1);
const auto up1 = upper_bound(bebek.begin(), bebek.end(), input2-1);

不要使用 C 宏 NULL。 C++ 有 nullptr 关键字。


您在搜索时将最小值和最大值调整为 +1 和 -1,这似乎很奇怪。 ..._bound 的定义与您要执行的操作相匹配,因此提供的数字应该是正确的。

“大于最小值”upper_bound 将指向大于数字的第一个元素。所以,你使用了错误的函数。

“低于或等于最大值”lower_bound 将指向第一个相等。 upper_bound 将指向第一个 greater,这意味着之前的那些是您想要的计数。

因此,您在第一次调用时使用了错误的绑定函数,并且您不应该更改输入的最小值/最大值。

【讨论】:

  • 您将有关风格的建议与非风格的建议混为一谈。此外,在某些情况下using namespace std; 可以,而在某些情况下则不行。只是说“不要那样做”并不能帮助理解为什么不使用它。
猜你喜欢
  • 1970-01-01
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多