Seems like you got already rid of the segmentation fault. For your problems with the time limit: Use somewhat faster IO. Either use scanf instead of cin, or start your program with
ios_base::sync_with_stdio ( false );
In that case don’t mix C-type IO with C+±type IO. I guess this should be enough to let your program pass the time limit. Concerning your logic just one thing: Look at the compare function, you forget a return (I didn’t think about the rest).
thanks for pointing mistake.