Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя sourchakcf

Автор sourchakcf, история, 2 года назад, По-английски
#include <bits/stdc++.h>
 
using namespace std;
 
typedef long long int ln;
 
int main ()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
 
    int t = 0;
    cin >> t;
 
    while (t--)
    {
        int n = 0;
        cin >> n;
 
        unordered_map <int, int> u;
 
        for (int i = 0; i < n; i++)
        {
            int val = 0;
            cin >> val;
 
            u[val] += 1;
        }
 
        int count = u.size();
 
        for (int i = 1; i <= n; i++)
        {
            cout << max (i, count) << " ";
        }
 
        cout << endl;
    }
 
    return 0;
}

The above code is giving TLE for Test case 7.

#include <bits/stdc++.h>
 
using namespace std;
 
typedef long long int ln;
 
int main ()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
 
    int t = 0;
    cin >> t;
 
    while (t--)
    {
        int n = 0, count = 0;
        cin >> n;
 
        map <int, int> u;
 
        for (int i = 0; i < n; i++)
        {
            int val = 0;
            cin >> val;
 
            u[val] += 1;
        }
 
        for (auto x : u)
        {
            count += 1;
        }
 
        for (int i = 1; i <= n; i++)
        {
            cout << max (i, count) << " ";
        }
 
        cout << endl;
    }
 
    return 0;
}

But the above code is accepted.

Doesn't an unordered map take amortized o(1) whereas a map takes o(log(n))?

  • Проголосовать: нравится
  • -3
  • Проголосовать: не нравится

»
2 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

There's some evil black magic about specific inputs that can make std::unordered_map run in O(n) per query instead of O(1) amortized. You can read about it in the linked blog. However, std::map doesn't have this weakness, and is guaranteed to run in O(log n) time, thus won't TLE.