Good pairs#9642

Good pairs (Editorial)

Let's rewrite the condition a_i + a_j > b_i + b_j in the following form:

a_i - b_i > – ( a_j - b_j)

Let's construct an array of differences , where c_i = a_i - b_i. Sort the array c in non-decreasing order. The inequality a_i - b_i > - ( a_j - b_j) is equivalent to c_i > - c_j, or, equivalently, c_j > - c_i. This inequality can also be written as:

c_i + c_j > 0

Now, for each index i~(0 \le i \le n - 1), we need to find the smallest index such that c_j > - c_i. For all indices satisfying j \le k \le n - 1, the pairs will be good. However, to avoid counting pairs twice, we should only consider those for which k > i.

Example

Let’s consider the given example. Sort the array c_i = a_i - b_i in ascending order.

Let's take i = 0. We are looking for the smallest index such that c_j > - c_0 = 3. The smallest such index is j = 4. Therefore, the index pairs and are good.

Let's take i = 1. We are looking for the smallest index such that c_j > - c_1 = 1. The smallest such index is j = 3. Therefore, the index pairs (1, 3), (1, 4) and are good.

Let's take i = 2. We are looking for the smallest index such that cj > - c_2 = 0. The smallest such index is j = 3. Therefore, the index pairs (2, 3), (2, 4) and are good.

Let's take i = 3. We are looking for the smallest index such that c_j > - c_3 = -3. The smallest such index is j = 1. A pair is considered good if two conditions are met: k \ge j and k > i. In this case, the good pairs are and . The pairs and are also good, but they have already been counted earlier when considering i = 1 (pair ) and i = 2 (pair ).

Let's take i = 4. The only good pair in this case is .

In total, there are good index pairs.

Algorithm implementation

Read the input data.

scanf("%d", &n);
a.resize(n); b.resize(n); 
for (i = 0; i < n; i++)
  scanf("%d", &a[i]);
for (i = 0; i < n; i++)
  scanf("%d", &b[i]);

Build an array of differences , where c_i = a_i - b_i.

c.resize(n);
for (i = 0; i < n; i++)
  c[i] = a[i] - b[i];

Sort the array in ascending order.

sort(c.begin(), c.end());

Count the number of good index pairs in the variable .

res = 0;

Iterate over the indices .

for (i = 0; i < n; i++)
{

For each index , find the smallest index such that c_{pos} > - c_i. At the same time, the condition pos \ge i + 1 must be satisfied.

  pos = lower_bound(c.begin() + i + 1, c.end(),-c[i] + 1) - c.begin();

All index pairs such that pos \le k \le n - 1 will be good. The number of such values of is (n - 1) - pos + 1 = n - pos.

  res += n - pos;
}

Print the answer.

printf("%lld\n", res);