Блог пользователя hxano

Автор hxano, история, 2 месяца назад, По-английски

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.

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

»
2 месяца назад, # |
  Проголосовать: нравится -55 Проголосовать: не нравится

I think ++n increases the value first, while n++ increases the value later. That's the difference.

»
2 месяца назад, # |
  Проголосовать: нравится +30 Проголосовать: не нравится

I believe this is UB. You can read more about it in the link below. It uses a similar case a[i] = i++; as an example of UB.

https://en.m.wikipedia.org/wiki/Sequence_point

»
2 месяца назад, # |
Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится

In a[++n] = n, first right hand expression is calculated then left hand is calculated, so let's say n was equal to 5 earlier, this expression iss then equivalent to

a[6] = 5 and sets n to 6;

instead if you use the expression

a[n] = ++n;

which sets n to 6 first, which is equivalent to a[6] = 6 if n was 5 initially.

»
2 месяца назад, # |
  Проголосовать: нравится -21 Проголосовать: не нравится

As per my research and knowledge, this happens primarily because, the programming languages handle these operations internally is different. For example, the same statements may work for other languages like Java.

»
2 месяца назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

It's possible that Codeforces is compiling with a different compiler or different version than you are using locally. I'm not entirely sure, but I don't think that such behavior is strictly defined. Also, compilers perform a lot of optimization. Any of these factors could cause what you are seeing here.