1+ const local_input = `
2+ 8
3+ 6 15 21
4+ 7 20 25
5+ 1 3 8
6+ 3 2 14
7+ 8 6 27
8+ 2 7 13
9+ 4 12 18
10+ 5 6 20
11+ ` ;
12+
13+ const input = process . execArgv . includes ( "--stack-size=65536" )
14+ ? require ( "fs" ) . readFileSync ( "dev/stdin" ) . toString ( )
15+ : local_input ;
16+
17+ const lines = input . trim ( ) . split ( "\n" ) ;
18+ const sorted = lines
19+ . slice ( 1 )
20+ . map ( el => el . split ( ' ' ) . map ( Number ) )
21+ . sort ( ( a , b ) => a [ 1 ] - b [ 1 ] ) ;
22+
23+ // console.log(sorted);
24+
25+ class MinHeap {
26+ constructor ( ) {
27+ this . heap = [ ] ;
28+ }
29+
30+ push ( value ) {
31+ this . heap . push ( value ) ;
32+ let idx = this . heap . length - 1 ;
33+
34+ while ( idx > 0 && this . heap [ idx ] < this . heap [ this . getParent ( idx ) ] ) {
35+ this . swap ( idx , this . getParent ( idx ) ) ;
36+ idx = this . getParent ( idx ) ;
37+ }
38+ }
39+
40+ getParent ( index ) {
41+ return Math . floor ( ( index - 1 ) / 2 ) ;
42+ }
43+
44+ getLeft ( index ) {
45+ return index * 2 + 1 ;
46+ }
47+
48+ getRight ( index ) {
49+ return index * 2 + 2 ;
50+ }
51+
52+ swap ( index1 , index2 ) {
53+ const temp = this . heap [ index1 ] ;
54+ this . heap [ index1 ] = this . heap [ index2 ] ;
55+ this . heap [ index2 ] = temp ;
56+ }
57+
58+ pop ( ) {
59+ if ( ! this . heap . length ) {
60+ return null ;
61+ }
62+
63+ const min = this . heap [ 0 ] ;
64+ const last = this . heap . pop ( ) ;
65+
66+ if ( this . heap . length ) {
67+ this . heap [ 0 ] = last ;
68+
69+ let idx = 0 ;
70+
71+ while ( this . getLeft ( idx ) < this . heap . length ) {
72+ const left = this . getLeft ( idx ) ;
73+ const right = this . getRight ( idx ) ;
74+
75+ let minChild = left ;
76+
77+ if ( right < this . heap . length && this . heap [ right ] < this . heap [ left ] ) {
78+ minChild = right ;
79+ }
80+
81+ if ( this . heap [ idx ] < this . heap [ minChild ] ) {
82+ break ;
83+ }
84+
85+ this . swap ( idx , minChild ) ;
86+ idx = minChild ;
87+ }
88+ }
89+
90+ return min ;
91+ }
92+ }
93+
94+ const minHeap = new MinHeap ( ) ;
95+
96+ let result = 0 ;
97+
98+ sorted . forEach ( el => {
99+ minHeap . push ( el [ 2 ] ) ;
100+
101+ if ( minHeap . heap [ 0 ] <= el [ 1 ] ) {
102+ minHeap . pop ( ) ;
103+ } else {
104+ result ++ ;
105+ }
106+ } )
107+
108+ console . log ( result )
0 commit comments