The problem is that you are given the positions of bishops on a big chessboard, and you are to count the number of pairs of bishops that share a diagonal (i.e. could attack each other, if no other bishops were in the way).
The insight that makes this code work is that you can start with an empty board, and account for all the possible bishop pairs by saying that each pair is between a bishop already on the board and a new bishop being added.
The basic algorithm here is that a
counts the number of bishops on each diagonal running in one direction (upper-left to lower-right, if x counts across and y counts down), and b
counts the number of bishops on each diagonal running in the other, perpendicular direction (upper-right to lower-left).
You can use x+y
to get which upper-left-to-lower-right diagonal the current bishop lands on. It will form a pair with each other bishop already placed on the diagonal, so you add in a[x+y]
to your sum. Then you increment a[x+y]
, because you just put a new bishop on that diagonal.
Similarly with the other diagonal: work out which diagonal you are going to with x-y
, add the number of bishops already on the diagonal (and thus the number of new pairs formed) into the sum, and then increment the diagonal's bishop count.
The 1000+
is there to prevent the array index from becoming negative, because x-y
can be negative when x
is 0. The arrays are made excessively big because the programmer didn't bother working out how small they could safely be. The program exploits rule 3.6.2 of the C++ standard which guarantees that static-storage-duration variables (like all those globals) will be 0-initialized.