# C++ program to count in how many ways we can minimize cable length to connect computers

C++Server Side ProgrammingProgramming

Suppose we have two arrays A and B both with N elements. Consider there are N computers and N sockets. The coordinate of ith computer is A[i] and coordinate of ith socket is b[i]. These 2N coordinates are pair-wise distinct. We want to connect each computer with a socket by cables. Each socket can be connected at most one computer. We have to count in how many ways we can minimize the length of cables. If the answer is too large, return result mod 10^9 + 7.

So, if the input is like A = [0, 10]; B = [20, 30], then the output will be 2, because there are two optimal connections, (0 to 20, 10 to 30) and (0 to 30, 10 to 20). In both cases, the total length of cables is 40.

## Steps

To solve this, we will follow these steps −

maxn := 200005
p := 10^9 + 7
Define one array of pair for integer type elements
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
first element of a[i] := A[i]
second element of a[i] := 1
for initialize i := n, when i < 2 * n, update (increase i by 1), do:
first element of a[i] := B[i - n]
second element of a[i] := -1
sort the array a
ways := 1, val = 0
for initialize i := 0, when i < 2 * n, update (increase i by 1), do:
if val * second element of a[i] < 0, then:
ways := ways * |val|
val := val + (second element of a[i])
return ways

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(vector<int> A, vector<int> B){
long maxn = 200005;
long p = 1000000007;
pair<int, int> a[maxn];
int n = A.size();
for (int i = 0; i < n; i++){
a[i].first = A[i];
a[i].second = 1;
}
for (int i = n; i < 2 * n; i++){
a[i].first = B[i - n];
a[i].second = -1;
}
sort(a, a + 2 * n);
long long ways = 1, val = 0;
for (int i = 0; i < 2 * n; i++){
if (val * a[i].second < 0){
ways = ways * abs(val) % p;
}
val += a[i].second;
}
return ways;
}
int main(){
vector<int> A = { 0, 10 };
vector<int> B = { 20, 30 };
cout << solve(A, B) << endl;
}

## Input

{ 0, 10 }, { 20, 30 }

## Output

2