from collections import deque from heapq import heappop, heappush from typing import List, Tuple INF = int(1e18) def minCostCycle(n: int, edges: List[Tuple[int, int, int]], directed: bool) -> int: """O(V*(V+E)*logV)求最小环权值之和,不存在返回INF.""" res = INF maxWeight = max(w for *_, w in edges) res = INF for i, e1 in enumerate(edges): from_, to, weight = e1 adjList = [[] for _ in range(n)] for j, e2 in enumerate(edges): if i != j: u, v, w = e2 adjList[u].append((v, w)) if not directed: adjList[v].append((u, w)) cand = _bfs01(adjList, from_, to) if maxWeight <= 1 else _dijkstra(adjList, from_, to) res = min(res, weight + cand) return res def _bfs01(adjList: List[List[Tuple[int, int]]], start: int, target: int) -> int: n = len(adjList) dist = [INF] * n dist[start] = 0 queue = deque([start]) while queue: cur = queue.popleft() if cur == target: return dist[cur] for next, weight in adjList[cur]: cand = dist[cur] + weight if cand < dist[next]: dist[next] = cand if weight == 0: queue.appendleft(next) else: queue.append(next) return INF def _dijkstra(adjList: List[List[Tuple[int, int]]], start: int, target: int) -> int: n = len(adjList) dist = [INF] * n dist[start] = 0 pq = [(0, start)] while pq: curDist, cur = heappop(pq) if cur == target: return curDist if dist[cur] < curDist: continue for next, weight in adjList[cur]: cand = curDist + weight if cand < dist[next]: dist[next] = cand heappush(pq, (cand, next)) return INF if __name__ == "__main__": directed = int(input()) n, m = map(int, input().split()) edges = [] for _ in range(m): u, v, w = map(int, input().split()) u -= 1 v -= 1 edges.append((u, v, w)) res = minCostCycle(n, edges, directed == 1) if res == INF: res = -1 print(res)