The concept you need to understand this problem is that the amount of internal energy in your system is a state function. That means it depends only on the temperature, pressure etc of your system and not on the path taken to reach that state.
In this case no heat enters or leaves your system so the amount of heat is constant. What actually happens is the melting ice cools the condensing steam and they meet somewhere in the middle. But we could imagine a different path.
Suppose we inject heat into the system to melt the ice, then boil the water to make steam at 100°C. And suppose we have to put in some heat $H$ to do this. Now we have 40g of steam at 100°C. Then we let the steam condense, then cool, until we get the same amount of heat $H$ out again. Now we reach a state where the net amount of heat hasn't changed, and because internal energy is a state function this must be the same state that we would have reached by letting the steam and ice interact directly.
Or alternatively suppose we let the steam condense, then cool to 0°C, then freeze, and we get out some amount of heat $H$ by doing this. This gives us 40g of ice at 0°C. Now we put the same amount of heat $H$ back in to melt the ice, then heat the water, and once again we reach the same state. So this will give us the same result as the two processes above.
We often show the process as diagrams like this:
So the left diagram shows us putting in heat $H$ to make steam then taking it out again, while the right diagram shows us taking out heat to make ice then putting it back in again. Because in both cases the net change in the heat is zero the two final states must be the same, and both will be the same as if we just let the ice cool the steam directly.