Runtime Error in C++17 but Accepted in C++20 and C++23. Why?

Правка en1, от shashank2401, 2025-01-05 02:14:54

Hello, everyone!

I was solving the problem 2057B - Gorilla and the Exam from the Hello 2025 round and I encountered some weird compiler-level issues.

Problematic Code in C++17

void solve() {
    ll n,k;
    cin>>n>>k;
    vector<ll>v(n);
    map<ll,ll>m;
    for(ll i=0; i<n; i++){
        cin>>v[i];
        m[v[i]]++;
    }
    vector<ll>counts;
    for(auto&i:m) counts.pb(i.ss);
    sort(all(counts));
    ll cnt=0;
    ll sz=0;
    for(ll i=0; i<n; i++){
        cnt+=counts[i];
        if(cnt <= k) sz++;
        else break;
    }
    if(k==n) cout<<1<<endl;
    else cout<<m.size()-sz<<endl;
    return;
}

In this code, I encountered a Runtime Error on Test 24 when I used C++17. However, the same code worked perfectly fine in both C++20 and C++23.

Modified Code that worked in C++17

Surprisingly, this also worked in C++17 when I changed some ll to int, as shown below.

void solve() {
    ll n,k;
    cin>>n>>k;
    vector<ll>v(n);
    map<ll,ll>m;
    for(ll i=0; i<n; i++){
        cin>>v[i];
        m[v[i]]++;
    }
    vector<int>counts; //changed ll to int in this line
    for(auto&i:m) counts.pb(i.ss);
    sort(all(counts));
    ll cnt=0;
    ll sz=0;
    for(int i=0; i<n; i++){
        //changed ll to int in the line above
        cnt+=counts[i];
        if(cnt <= k) sz++;
        else break;
    }
    if(k==n) cout<<1<<endl;
    else cout<<m.size()-sz<<endl;
    return;
}

Can anyone explain what's happening here? Why does the first code give a Runtime Error when using C++17, and how does it magically work when I change some ll to int?

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский shashank2401 2025-01-05 02:14:54 1730 Initial revision (published)