import random import sys # ユークリッド距離を計算する関数 def euclidean_distance(point1, point2): return sum((a - b) ** 2 for a, b in zip(point1, point2)) ** 0.5 # K-meansクラスタリングを手動で実装 def initialize_centroids(points, k): return random.sample(points, k) def assign_clusters(points, centroids): clusters = [] for point in points: distances = [euclidean_distance(point, centroid) for centroid in centroids] cluster = distances.index(min(distances)) clusters.append(cluster) return clusters def update_centroids(points, clusters, k): new_centroids = [] for i in range(k): cluster_points = [points[j] for j in range(len(points)) if clusters[j] == i] if cluster_points: new_centroid = [sum(dim) / len(cluster_points) for dim in zip(*cluster_points)] new_centroids.append(tuple(new_centroid)) return new_centroids def kmeans(points, k, max_iters=100): centroids = initialize_centroids(points, k) for _ in range(max_iters): clusters = assign_clusters(points, centroids) new_centroids = update_centroids(points, clusters, k) if centroids == new_centroids: break centroids = new_centroids return clusters, centroids def HeldKarp(dists): # 厳密解(HeldKarp), O(N^2 * 2^N) # dists[x][y]:xy間の距離 N = len(dists) # 都市数 dp = [[10**18] * N for _ in range(2**N)] for i in range(N): # 地点0から最初の訪問地までの距離(スタートは地点0としている) dp[1<