#P4889. Excellent Bamboo Poles
Excellent Bamboo Poles
Excellent Bamboo Poles
There are n bamboo poles placed in a row at unit distance apart. Each pole is initially vertical and has an integer height between 1 and m (inclusive). Each bamboo pole can fall either to the left or to the right. When a bamboo falls, it lies horizontally, and its tip will move from its original position. Specifically, if a pole located at position i with height a falls to the left, its tip lands at position i - a; if it falls to the right, its tip lands at position i + a (positions are 1-indexed).
We call a pair of poles excellent if there exists a choice of falling directions for the two poles such that their tips coincide. It turns out that, after analyzing all the possible combinations, two poles at positions i and j (with i < j) with heights a and b respectively will form an excellent pair if and only if one of the following conditions holds:
- Case 1 (One falls right and the other falls left): The tips coincide if \[ i + a = j - b \quad \Longleftrightarrow \quad j - i = a + b. \]
- Case 2 (Both fall to the right): The tips coincide if \[ i + a = j + b \quad \Longleftrightarrow \quad a - b = j - i, \quad \text{which is possible when } a > b. \]
- Case 3 (Both fall to the left): The tips coincide if \[ i - a = j - b \quad \Longleftrightarrow \quad b - a = j - i, \quad \text{which is possible when } b > a. \]
In summary, two poles at positions i and j (with i < j) with heights a and b are excellent if and only if
[ j - i = a + b \quad \text{or} \quad j - i = |a - b|. ]
Your task is to count the number of excellent pairs among the given bamboo poles.
inputFormat
The first line contains two integers n and m where n is the number of bamboo poles and m is the maximum possible height.
The second line contains n integers h1, h2, ..., hn where hi denotes the height of the bamboo at position i (1-indexed).
outputFormat
Output a single integer representing the total number of excellent pairs.
sample
5 10
1 2 3 2 1
8