Replacing cin cout with scanf printf

I was solving the problem Chef and Strings appeared in the Long challenge of Feb 15 and I got AC in the first 2 subtasks and tle in the 3rd.
(here’s the link : http://www.codechef.com/viewsolution/6307251 )

I figured to switch to scanf instead of cin to reduce query time for 10^6 queries.

But the I ended up getting SIGSEGV for all 3 sub tasks.
(here’s the link for the modified code : http://www.codechef.com/viewsolution/6307266 )

I obviously am doing something wrong but still I’m unable to figure out what exactly. Would appreciate if someone would like to chip in.

Thanks

Here is an FAQ on SIGSEGV

I don’t why but “cin>>S” is causing the SIGSEGV. see this solution http://www.codechef.com/viewsolution/6319065 .

1 Like

Thanks for the help man. Though I thought simple replacing cin cout with scanf printf will avoid tle. Seems like maintaining a hashmap is a bad idea. Still don’t know why though. Maybe it’s the log(12) factor in accessing a key.

There are two problem here, second one is because you are using a input stream reading method which leaves the ‘\n’ (new line ).

  1. You are disabling sync with stdio ( in your macro std::ios_base::sync_with_stdio(false).

With stdio synchronization turned off, iostream standard stream objects may operate independently of the standard C streams (although they are not required to), and mixing operations may result in unexpectedly interleaved characters., read about it here.

For fast I/O (which is what you are trying to achieve here) you may want to turn sync off but in that case You can’t use both cin/cout and printf/scanf., this is mentioned here.

This mixing is what gives you weird input chars at the line scanf("%c %c %d %d",&a,&b,&i,&j); ( which does not happen in case of @diptesh1ce3 as he/ she is avoiding mixing and this is why his solution passes).

  1. You need to reads the newline left afterwards, very obviously just use scanf("%d",&ch). Read this if you want more help regarding this or at stackoverflow.

Check your code ACcepted here with the said problems rectified ( kept your mixed cin/scanf approach ).

This answer deals only with the reason why runtime error occurred, not how to pass subtask 3, I also wasn’t able to pass the subtask 3 using segment tree during contest :’( .

3 Likes