ideone.com/vOZRSb
Your algorithm is O(n^3). With n being as large as 10000 that's far too slow. Do you really need all three loops?
i think 3 loops are required. what else can be done?
You will not get AC with three loops You must figure that out on your own, that is the whole difficulty of the problem.