You can get AC with this approach, but your way of reading the input is too slow for the large amount of data that has to be processed.
How to do that is what you have to figure out yourself:
Generate some random data (easy for that problem) and check the runtime of some variants.
And perhaps code should be removed. 