import sys from time import time from random import randrange START = time() INF=10**9 class Node: def __init__(self, isTerminal: bool, idx: int, pos: list): self.isTerminal = isTerminal self.idx = idx self.pos = pos self.dist = INF def __str__(self): return "{} {}".format(2-self.isTerminal, self.idx) def get_time(START): return time() - START def dist(p1,p2): x1,y1=p1 x2,y2=p2 return (x1-x2)**2 + (y1-y2)**2 def calc(idx: int): d = dist(ans[idx].pos, ans[idx+1].pos) if ans[idx].isTerminal and ans[idx+1].isTerminal: a = 25 elif ans[idx].isTerminal or ans[idx+1].isTerminal: a = 5 else: a = 1 return a * d N,M=map(int,input().split()) Terminals = [list(map(int,input().split())) for _ in range(N)] ans = [Node(True,1,Terminals[0])] candidates = set(range(1,N)) for _ in range(N-1): best_index = -1 best_dist = INF for cand in candidates: d = dist(ans[-1].pos, Terminals[cand]) if d < best_dist: best_dist = d best_index = cand assert best_index!=-1 ans.append(Node(True, best_index+1, Terminals[best_index])) candidates.discard(best_index) ans.append(Node(True,1,Terminals[0])) n = len(ans) loop_cnt1 = 0 while get_time(START) < 0.95: loop_cnt1+=1 v1 = randrange(1,n-1) v2 = randrange(1,n-1) while v1==v2: v2 = randrange(1,n-1) current_score = calc(v1-1) + calc(v1) + calc(v2-1) + calc(v2) ans[v1],ans[v2] = ans[v2],ans[v1] changed_score = calc(v1-1) + calc(v1) + calc(v2-1) + calc(v2) if changed_score < current_score: continue else: ans[v1],ans[v2] = ans[v2],ans[v1] candidates = [] for i in range(N): d = dist(ans[i].pos, ans[i+1].pos) candidates.append([i,d]) candidates.sort(key=lambda x:x[1], reverse=1) Stations = [] for i,cand in enumerate(candidates[:M], start=1): idx = cand[0] Stations.append(Node(False, i, ans[idx].pos)) for station in Stations: for i in range(len(ans)): if ans[i].pos == station.pos: ans.insert(i+1, station) break bestScore = 0 loop_cnt2 = 0 idx=0 while True: if idx >= len(ans)-1: break if not ans[idx].isTerminal and not ans[idx+1].isTerminal: idx += 1 continue if ans[idx].isTerminal and ans[idx+1].isTerminal: a = 25 else: a = 5 cur_dist = a * dist(ans[idx].pos,ans[idx+1].pos) best_dist = cur_dist best_station = station for station in Stations: a1 = 5 if ans[idx].isTerminal else 1 a2 = 5 if ans[idx+1].isTerminal else 1 _dist = a1 * dist(ans[idx].pos, station.pos) + a2 * dist(station.pos, ans[idx+1].pos) if _dist < best_dist: best_dist = _dist best_station = station if best_dist != cur_dist: ans.insert(idx+1, best_station) idx += 2 else: idx += 1 for node in Stations: print(*node.pos) print(len(ans)) for node in ans: print(node) print("Loop1", loop_cnt1, file=sys.stderr) print("Loop2", loop_cnt2, file=sys.stderr) print("time:",get_time(START) * 1000, file=sys.stderr)