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

Правка en3, от hxano, 2024-11-15 10:18:22

I was solving 1839D - Ball Sorting 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 solution 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.

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en3 Английский hxano 2024-11-15 10:18:22 1 Tiny change: 'n\nWA soluion vs AC ' -> 'n\nWA solution vs AC '
en2 Английский hxano 2024-09-08 06:09:40 5 Tiny change: ' [problem:876D] which w' -> ' [problem:1839D] which w'
en1 Английский hxano 2024-09-07 20:51:00 1312 Initial revision (published)