-
Notifications
You must be signed in to change notification settings - Fork 0
/
App6_MST_Kruskal.py
86 lines (73 loc) · 2.78 KB
/
App6_MST_Kruskal.py
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
# this MST approach (Kruskal's algorithm)
import math
def euclidean_distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def orienteering_problem_kruskal(input_file, output_file):
# Read input from the file
with open(input_file, 'r') as file:
lines = file.readlines()
# Parse the input
Tmax, P = map(int, lines[0].split())
points = []
for line in lines[1:]:
x, y, score = map(float, line.split())
points.append((x, y, score))
# Calculate the distance matrix
n = len(points)
distance_matrix = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(i+1, n): # Utilize symmetry of the distance matrix
dist = euclidean_distance(
points[i][0], points[i][1], points[j][0], points[j][1])
distance_matrix[i][j] = dist
distance_matrix[j][i] = dist
# Create the edges list with "score - cost" values
edges = []
for i in range(n):
for j in range(i+1, n):
edge_score = points[j][2] - distance_matrix[i][j]
edges.append((i, j, edge_score))
# Sort the edges list by the "score - cost" value in descending order
edges.sort(key=lambda x: x[2], reverse=True)
# Initialize the parent array for Union-Find
parent = [i for i in range(n)]
# Find the parent of a node using Union-Find algorithm
def find_parent(node):
if parent[node] == node:
return node
parent[node] = find_parent(parent[node])
return parent[node]
# Perform Kruskal's algorithm
mst = []
total_profit = 0
total_cost = 0
edge_count = 0
for edge in edges:
u, v, _ = edge
parent_u = find_parent(u)
parent_v = find_parent(v)
if parent_u != parent_v and total_cost + distance_matrix[u][v] <= Tmax:
parent[parent_u] = parent_v
mst.append(edge)
total_profit += points[v][2]
total_cost += distance_matrix[u][v]
edge_count += 1
if edge_count == n - 1:
break
# Write the output to the file
with open(output_file, 'w') as file:
file.write("MST Edges:\n")
for edge in mst:
file.write(f"{edge[0]+1} - {edge[1]+1}\n")
file.write("\n")
file.write(f"Total Profit: {total_profit}\n")
file.write(f"Total Cost: {total_cost}")
print("MST Edges:")
for edge in mst:
print(f"{edge[0]+1} - {edge[1]+1}")
print(f"Total Profit: {total_profit}")
print(f"Total Cost: {total_cost}")
# Usage example
input_file = 'Dataset/set_64_1_80.txt'
output_file = 'Results/set_64_1_80_App6.txt'
orienteering_problem_kruskal(input_file, output_file)