【问题标题】:Time complexity issue in c++c++中的时间复杂度问题
【发布时间】:2022-06-10 18:55:08
【问题描述】:

谁能帮我找出代码如何运行超过 2 秒?其中 1 ≤ N ≤ 10^6 和 1 ≤ Q ≤ 2⋅10^5。由于 push_back 函数到向量的时间复杂度为 O(1),而从 unordered_map 访问的时间复杂度也为 O(1)。

#include<iostream>
#include<unordered_map>
#include<vector>

using namespace std;

bool check[1000000];

int main() {
    int N, Q, n;
    bool c = false;
    int last_reset[2] = {0,0};
    string Y;
    cin >> N >> Q;
    unordered_map<int,pair<int,int>> J;
    vector<int> H;
    for (int i = 0; i < Q; i++)
    {
        cin >> Y >> n;
        if(Y=="SET") m = 1;
        else if(Y=="RESTART") m = 2;
        else m = 3;
        switch (m)
        {
        case 1:
            cin >> u;
            check[n-1] = true;
            J[n] = {u,i+1};
            break;
        case 2:
            c = true;
            last_reset[0] = n;
            last_reset[1] = i+1;
            break;
        case 3:
            if (c && check[n-1] && last_reset[1] > J[n].second)
                H.push_back(last_reset[0]);
            else if (c && check[n-1] && last_reset[1] < J[n].second)
                H.push_back(J[n].first);
            else if(check[n-1] && !c)
                H.push_back(J[n].first);
            else if(!check[n-1] && c)
                H.push_back(last_reset[0]);
            else
                H.push_back(0);
            break;
        default:
            break;
        }
    }
    
    for (auto i:H)
        cout << i << endl;
    
    return 0;
}

【问题讨论】:

  • "并且从地图访问的时间复杂度也为 O(1)。"那是不对的。无论如何,复杂性是关于渐近行为的,它很少告诉你关于固定输入大小的运行时间
  • std::vector 具有 O(1) 的 amortised 复杂性 - 如果您提前 reserve 有足够的空间,您将得到 O(1),否则可能会发生重新分配.哈希映射也一样——但 std::unordered_mapstd::map 是一个复杂度为 O(log(n))...树映射
  • 另外,您应该使用更具描述性的变量名称。 JYH 等单字母名称使代码难以理解。
  • 并重现你需要告诉输入的问题
  • 如果 Q 足够大,您会陷入死循环,除非您使用的是 short 超过典型 16 位的特殊机器...

标签: c++ time-complexity big-o


【解决方案1】:

for (short i = 0; i &lt; Q; i++) -- Q 是一个 int,但由于某种原因,我决定将 i 设为 short,这就是导致错误的问题....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多