This is what happened:
I was working on a WQS-Binary Search(Alien's Trick) problem today: CF125E. It's a template with many details; I wrote a bit over 100 lines of code. However, a few Runtime Errors (RE) submissions piqued my interest.
First was this RE on test 11: link. It was submitted using C++23. Then, without changing the code itself, I just switched the language to C++17, and it became WA (Wrong Answer) on test 14. The Checker Log showed Exit code is -1073741819.
After some debugging, it became RE on test 18: link. After some investigation, I suspected the issue might be with my sorting function. I had two sorting functions. The first sorted edges by weight ascending, and if weights were equal, edges connected to node 1 would be placed first. The second function reversed that priority for equal weights.
bool cmp1(edge x,edge y){
if(x.w==y.w) return (x.u==1 || x.v==1);
return x.w < y.w;
}
bool cmp2(edge x,edge y){
if(x.w==y.w) return (y.u==1 || y.v==1);
return x.w < y.w;
}
I recalled encountering mysterious REs twice before on a similar problem on Luogu: my submission records, scoring 30 and 40 points respectively. Back then, modifying the sort function also fixed it.
So, I made a change: I manually recorded whether an edge was connected to node 1 within the struct, like this:
struct edge{
int u, v, w, id;
bool is1;
};
bool cmp1(edge x, edge y){
if(x.w == y.w) return x.is1 > y.is1;
return x.w < y.w;
}
bool cmp2(edge x, edge y){
if(x.w == y.w) return x.is1 < y.is1;
return x.w < y.w;
}
Submitting this with C++20 worked and passed. It also passed with C++17.
I feel this is an important issue for me since it's happened two days in a row. I urgently want to understand the root cause of the REs to prevent similar problems in the future. Thank you.
Translated by Deepseek.








But I can passed p5633 on Luogu with these wrong codes,it's so mysterious.
They're my wrong codes on this problem yesterday:
Chinglish
Your original functions
do not define a strict weak ordering.
For example, suppose you have two edges
aandbsuch that:a.w == b.wa.u == 1,b.u == 1Then:
This violates asymmetry, which is one of the core properties of strict weak ordering.
What is a strict weak ordering?
A strict weak ordering is a binary relation $$$ \lt $$$ on a set $$$S$$$ that satisfies:
Your comparator violates asymmetry. As a result, using it in
std::sortorstd::stable_sortleads to undefined behavior, which can manifest as runtime errors, especially in optimized builds or different C++ standard versions.This explains why your original code crashed in some configurations but passed in others — undefined behavior is unpredictable.
thx.Undefined behavior in C++ is truly mysterious.
https://mirror.codeforces.com/blog/entry/70237