-
Notifications
You must be signed in to change notification settings - Fork 2
/
MinSpantree.swift
95 lines (71 loc) · 2.1 KB
/
MinSpantree.swift
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
//
// main.swift
// MinSpantreeSwift
//
// Created by Carl Friess on 03/05/16.
// Copyright © 2016 Carl Friess. All rights reserved.
//
import Foundation
class Scanner {
let source = NSFileHandle.fileHandleWithStandardInput()
var buffer: NSScanner?
func nextInt() -> Int {
if buffer == nil || buffer!.atEnd {
if let nextInput = NSString(data: source.availableData, encoding: NSUTF8StringEncoding) {
buffer = NSScanner(string: nextInput as String)
}
}
var value: Int = -1;
buffer!.scanInteger(&value)
return value
}
}
class Vertex {
var value: Int = 0
var parent: Vertex? = nil
init(value: Int) {
self.value = value
parent = self
}
func getRoot() -> Vertex {
return self.parent === self ? self : self.parent!.getRoot()
}
}
class Edge {
var u: Vertex? = nil
var v: Vertex? = nil
var weight = 0
init(u: Vertex, v: Vertex, weight: Int) {
self.u = u
self.v = v
self.weight = weight
}
}
let scanner = Scanner()
let numTests: Int = scanner.nextInt()
for test in 0..<numTests {
var numVertices = scanner.nextInt()
var numEdges = scanner.nextInt()
var vertices = [Vertex?](count: numVertices, repeatedValue: nil)
var edges = [Edge]()
for i in 0..<numEdges {
let uValue = scanner.nextInt() - 1
let vValue = scanner.nextInt() - 1
if vertices[uValue] == nil {
vertices[uValue] = Vertex(value: uValue)
}
if vertices[vValue] == nil {
vertices[vValue] = Vertex(value: vValue)
}
edges.append(Edge(u: vertices[uValue]!, v: vertices[vValue]!, weight: scanner.nextInt()))
}
edges.sortInPlace({ $0.weight < $1.weight })
var totalWeight = 0
for edge in edges {
if edge.u!.getRoot() !== edge.v!.getRoot() {
edge.v!.getRoot().parent = edge.u!.getRoot()
totalWeight += edge.weight
}
}
print(totalWeight)
}