简体   繁体   English

算法的最坏情况复杂度

[英]Worst case complexity of an algo

void my_algo(const std::vector<unsigned int>& lp, const std::vector<unsigned int>& lm, std::vector<int>& aff) {

  std::vector<std::pair<unsigned int, unsigned int> > m_index;
  for (unsigned int i = 0; i < m_lengths.size(); i++)
    m_index.push_back(std::make_pair(m_lenghts[i], i));

  std::vector<std::pair<unsigned int, unsigned int> > p_index;
  for (unsigned int i = 0; i < p_lengths.size(); i++)
    p_index.push_back(std::make_pair(p_lenghts[i], i));

  std::make_heap(p_index.begin(), p_index.end());
  std::make_heap(m_index.begin(), m_index.end());

  for (unsigned int i = 0; i < m_lengths.size(); i++) {

    std::pop_heap(m_index.begin(), m_index.end());
    std::pair<unsigned int, unsigned int> m_root = m_index.back();
    m_index.pop_back();

    std::pop_heap(p_index.begin(), p_index.end());
    std::pair<unsigned int, unsigned int> p_root = p_index.back();
    p_index.pop_back();

    if (p_root.first >= m_root.first) {
      aff.at(m_root.second) = p_root.second;

      p_root.first -= m_root.first;
    }
    else{
      aff.at(m_root.second) = -1;
    }

    p_index.push_back(root_p);
    std::push_heap(p_index.begin(), p_index.end());
  }
}

I would like to analyze the worst case complexity of my algorithm, but I am not sure where to start.我想分析我的算法的最坏情况复杂性,但我不知道从哪里开始。 Suppose the length of lp is n and the length of lm is m.假设lp的长度为 n, lm的长度为 m。 The complexity of the two first for loop are quite easy but I am not sure about the third one.前两个 for 循环的复杂性很简单,但我不确定第三个。 Can you help with the worst case complexity of the algorithm?你能帮助解决算法的最坏情况复杂性吗?

I think third for loop might be in 2 m log(m), but I am really not sure of what I am saying.我认为第三个 for 循环可能在 2 m log(m) 中,但我真的不确定我在说什么。 Could you explain step by step how to analyse the last for loop?您能否逐步解释如何分析最后一个 for 循环?

The first loop and make_heap has complexity O(m) .第一个循环和 make_heap 的复杂度为O(m) The second loop and make_heap has complexity O(n) .第二个循环和 make_heap 的复杂度为O(n)

Now the third loop has m iterations, each of which does 1 m_index heap operation, and 2 p_index heap operations.现在第三个循环有m次迭代,每次迭代进行 1 个m_index堆操作和 2 个p_index堆操作。 Heap pop/push operations have cost logarithmic in number of elements.堆弹出/推送操作在元素数量上的成本是对数的。 Thus the cost is O(m (log(m)+log(n) ) . If m>=n then this is O(m log(m)) .因此成本为O(m (log(m)+log(n) ) 。如果m>=n则为O(m log(m))

Note that you can slightly improve your solution, by only pop'ing and push'ing p_root if it is actually altered.请注意,您可以稍微改进您的解决方案,仅在p_root实际被更改时弹出并推送它。

Instead of std::make_heap , std::pop_heap and std::push_heap over a std::vector , you can also directly use std::priority_queue instead.除了std::make_heapstd::pop_heapstd::push_heap std::vector您还可以直接使用std::priority_queue

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

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