File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const input = require ( 'fs' )
2+ . readFileSync ( process . platform === 'linux' ? '/dev/stdin' : './input.txt' )
3+ . toString ( )
4+ . trim ( )
5+ . split ( '\n' )
6+ . map ( Number ) ;
7+
8+ const G = input [ 0 ] ;
9+ const P = input [ 1 ] ;
10+ const planes = input . slice ( 2 ) ;
11+
12+ const parent = Array . from ( { length : G + 1 } , ( _ , i ) => i ) ;
13+
14+ function find ( x ) {
15+ if ( parent [ x ] === x ) return x ;
16+ return ( parent [ x ] = find ( parent [ x ] ) ) ;
17+ }
18+
19+ function union ( x , y ) {
20+ const rootX = find ( x ) ;
21+ const rootY = find ( y ) ;
22+ if ( rootX !== rootY ) {
23+ parent [ rootX ] = rootY ;
24+ }
25+ }
26+
27+ let answer = 0 ;
28+
29+ for ( let i = 0 ; i < P ; i ++ ) {
30+ const gate = planes [ i ] ;
31+ const availableGate = find ( gate ) ;
32+
33+ if ( availableGate === 0 ) break ;
34+
35+ union ( availableGate , availableGate - 1 ) ;
36+
37+ answer ++ ;
38+ }
39+
40+ console . log ( answer ) ;
Original file line number Diff line number Diff line change 1+ const input = require ( 'fs' )
2+ . readFileSync ( process . platform === 'linux' ? '/dev/stdin' : './input.txt' )
3+ . toString ( )
4+ . trim ( )
5+ . split ( '\n' )
6+ . map ( ( el ) => el . split ( ' ' ) . map ( Number ) ) ;
7+
8+ const N = input [ 0 ] [ 0 ] ;
9+ const lines = input . slice ( 1 ) . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
10+
11+ let totalLength = 0 ;
12+ let currentStart = lines [ 0 ] [ 0 ] ;
13+ let currentEnd = lines [ 0 ] [ 1 ] ;
14+
15+ for ( let i = 1 ; i < N ; i ++ ) {
16+ const [ start , end ] = lines [ i ] ;
17+
18+ if ( start <= currentEnd ) {
19+ currentEnd = Math . max ( currentEnd , end ) ;
20+ } else {
21+ totalLength += currentEnd - currentStart ;
22+ currentStart = start ;
23+ currentEnd = end ;
24+ }
25+ }
26+
27+ totalLength += currentEnd - currentStart ;
28+
29+ console . log ( totalLength ) ;
You can’t perform that action at this time.
0 commit comments