Inconsistency regarding (a[++n]=n)

Revision en1, by hxano, 2024-09-07 20:51:00

I was solving 876D - Sorting the Coins which was a standard DP problem, when I submitted and got WA on test 1. This was so strange to me since I just pasted the input into my own IDE and the outputs were identical. But sure enough, the moment I submitted the same exact solution, the output was different. I had to spam multiple submissions onto Codeforces to see what went wrong.

WA soluion vs AC solution

280230092 280230005

The only difference between these two pieces of code were ++n; a[n]=n; and a[++n]=n;. At first I thought, shouldn't these have the exact same effect? That's what my compiler told me!

After another WA on test 1-to-debug submission, I realised that it is possible that Codeforces' compiler had put the original value of $$$n$$$ into some temporary memory first, and only then update $$$n$$$ and put the temporary value back into the array.

I have used this kind of assignment a[++n]=n so many times, I'm surprised that only now I'm discovering this! Which is so dangerous because imagine the devastation this could have caused me in offline contests where you only get one chance.

Is it bad practice to put any thing but a single variable into the index of an array? I hope to learn more from all of you.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English hxano 2024-09-08 06:09:40 5 Tiny change: ' [problem:876D] which w' -> ' [problem:1839D] which w'
en1 English hxano 2024-09-07 20:51:00 1312 Initial revision (published)