Lucky, you can't throw the switch when the trolley is at A or B, because you still have to pass through it to get back to C, and once you get to C, it is thrown the way you last passed through, which means you go back to the leg you just left. Your method won't allow the trolley to use both routes. This fact demands that the throwing of the switch be triggered at C, so you need to keep track of where you came from, A or B.
That's the way the event sequence has to go.
I gave a good deal of thought to a mechanical solution, but couldn't think of a good way to throw the switch. It's a lot easier to direct the electrons to do the job, than an actual physical force.
I'm still working on the electrical schematic for this, I'm very rusty with relay logic, as I haven't used it in many years. I'm in the middle of step three of the algorithm. Richard, you get to do step four, but I'll be able to talk you through it.
BTW, I read the original post many times, and found it pretty clear, what the situation was. This is a tricky problem!