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
?