using
System;
using
System.Collections.Generic;
class
GFG
{
class
pair : IComparable<pair>
{
public
int
first, second;
public
pair(
int
first,
int
second)
{
this
.first = first;
this
.second = second;
}
public
int
CompareTo(pair other)
{
if
(
this
.first != other.first)
{
return
this
.first - other.first;
}
return
this
.second - other.second;
}
}
static
int
nCr(
int
n,
int
r,
int
[] f)
{
return
f[n] / f[r] * f[n - r];
}
static
int
NumberOfWaysToChooseKRanges(
int
[] L,
int
[] R,
int
N,
int
K)
{
int
[] f =
new
int
[N + 1];
f[0] = 1;
for
(
int
i = 1; i <= N; i++)
{
f[i] = f[i - 1] * i;
}
List<pair> preprocessed =
new
List<pair>();
for
(
int
i = 0; i < N; i++)
{
preprocessed.Add(
new
pair(L[i], 1));
preprocessed.Add(
new
pair(R[i] + 1, -1));
}
preprocessed.Sort();
int
ans = 0;
int
Cnt = 0;
for
(
int
i = 0; i < preprocessed.Count; i++)
{
if
(preprocessed[i].second == 1)
{
if
(Cnt >= K - 1)
{
ans += nCr(Cnt, K - 1, f);
}
Cnt++;
}
else
{
Cnt--;
}
}
return
ans;
}
static
void
Main()
{
int
N = 7, K = 3;
int
[] L = { 1, 3, 4, 6, 1, 5, 8 };
int
[] R = { 7, 8, 5, 7, 3, 10, 9 };
Console.WriteLine(NumberOfWaysToChooseKRanges(L, R, N, K));
}
}