Optimize goal changed.

Make goal changed approximately O(paths + targets), instead of something
much worse.

PR for travis.