1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Daniel Grzegorzewski
// while (clock()<=69*CLOCKS_PER_SEC)
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")

#define MP make_pair
#define PB push_back
#define ST first
#define ND second
#define int long long

using namespace __gnu_pbds;
using namespace std;

template <typename T>
using ordered_set =
    tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

//X.find_by_order(k); - zwraca iterator na k-ty element (numeracja od zerowego)
//X.order_of_key(k); - zwraca liczbę elementów ostro mniejszych niż k

typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<PII> VII;
typedef long long LL;

void init_ios() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
}

const uint64_t SEED = chrono::steady_clock::now().time_since_epoch().count();
mt19937_64 rng(SEED);

const int N = 5*(int)1e5 + 3;
const int MOD = (int)1e9 + 7;

int n, res, l[N], r[N], sil[N], inv[N], cnt[N];
VI child[N];
bool vis[N];

int fpow(int x, int y) {
  if (y == 0)
    return 1;
  if (y&1)
    return x*fpow(x, y-1)%MOD;
  int res = fpow(x, y/2);
  return res*res%MOD;
}

void dfs(int v) {
  vis[v] = true;
  ++cnt[v];
  for (int x: child[v])
    if (!vis[x])
      dfs(x);
}

signed main() {
  init_ios();
  sil[0] = 1;
  for (int i = 1; i < N; ++i)
    sil[i] = i*sil[i-1]%MOD;
  inv[N-1] = fpow(sil[N-1], MOD-2);
  for (int i = N-2; i >= 0; --i)
    inv[i] = (i+1)*inv[i+1]%MOD;
  cin >> n;
  for (int i = 1; i <= n; ++i)
    cin >> l[i] >> r[i];
  set<PII> s;
  for (int i = n; i >= 1; --i) {
    auto it = s.lower_bound({l[i], -1});
    VII rem;
    while (it != s.end() && (*it).ST <= r[i]) {
      PII el = *it;
      rem.PB(el);
      if (child[el.ND].empty() || child[el.ND][0] != i)
        child[el.ND].PB(i);
      ++it;
    }
    for (const auto& el: rem)
      s.erase(el);
    s.insert({l[i], i});
    s.insert({r[i], i});
  }
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= i; ++j)
      vis[j] = false;
    dfs(i);
  }
  for (int i = 1; i <= n; ++i)
    res = (res+inv[cnt[i]]*sil[cnt[i]-1])%MOD;
  cout<<res<<"\n";
}