Pairs Having Similar Elements

4

138 votes
Arrays, Data Structures, Easy, One-dimensional
Problem

Given an array, A, having N integers A1,A2,...,AN.Two elements of the array Ai and Aj are called similar iff Ai=Aj+1 or Aj=Ai+1 .
Also, the similarity follows transitivity. If Ai and Aj are similar and Aj and Ak are similar, then Ai and Ak are also similar. 
Note: i, j, and k are all distinct.

You need to find number of pairs of indices (i,j) such that i<j and Ai is similar to Aj.

Input

The first line contains a single integer N denoting number of elements in the array.
The second line contains N space separated integers where ith elements indicateAi.

Output

Output the number of pairs of indices (i,j) such that i<j and Ai is similar to Aj in a single line.

Constraints

1N106109Ai109

Sample Input
8
1 3 5 7 8 2 5 7
Sample Output
6
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

We have 6 possible pairs of indices which contain similar elements.
(1,6) : A1 and A6 are similar since 2=1+1.
(2,6) : A2 and A6 are similar since 3=2+1.
(1,2) : A1 and A6 are similar by transitivity since (A1,A6) and (A2,A6) are similar, so A1 and A2 are also similar.
(4,5) : A4 and A5 are similar since 8=7+1.
(5,8) : A5 and A8 are similar since 8=7+1
(4,8) : A4 and A8 are similar by transitivity since (A4,A5), (A5,A8) are similar, so A4 and A8 are also similar.

 

Editor Image

?