File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -549,6 +549,62 @@ if __name__ == "__main__":
549549
550550### Javascript
551551
552+ ``` js
553+ function kruskal (v , edges ) {
554+ const father = Array .from ({ length: v + 1 }, (_ , i ) => i)
555+
556+ function find (u ){
557+ if (u === father[u]) {
558+ return u
559+ } else {
560+ father[u] = find (father[u])
561+ return father[u]
562+ }
563+
564+ }
565+
566+ function isSame (u , v ) {
567+ let s = find (u)
568+ let t = find (v)
569+ return s === t
570+ }
571+
572+ function join (u , v ) {
573+ let s = find (u)
574+ let t = find (v)
575+ if (s !== t) {
576+ father[s] = t
577+ }
578+ }
579+
580+ edges .sort ((a , b ) => a[2 ] - b[2 ])
581+ let result = 0
582+ for (const [v1 , v2 , w ] of edges) {
583+ if (! isSame (v1, v2)) {
584+ result += w
585+ join (v1 ,v2)
586+ }
587+ }
588+ console .log (result)
589+ }
590+
591+
592+ async function main () {
593+ const rl = require (' readline' ).createInterface ({ input: process .stdin })
594+ const iter = rl[Symbol .asyncIterator ]()
595+ const readline = async () => (await iter .next ()).value
596+ const [v , e ] = (await readline ()).split (" " ).map (Number )
597+ const edges = []
598+ for (let i = 0 ; i < e ; i++ ) {
599+ edges .push ((await readline ()).split (" " ).map (Number ))
600+ }
601+ kruskal (v, edges)
602+ }
603+
604+
605+ main ()
606+ ```
607+
552608### TypeScript
553609
554610### PhP
You can’t perform that action at this time.
0 commit comments