Fast Algorithm

시간 제한2초메모리 제한2048 MB

요약
약하게 연결된 방향 그래프에서 간선 가중치 합이 최소인 사이클을 찾아 그 값을 출력한다. m - n은 1500 이하이다.
난이도

어려움10점 중 8점

유형
최단 경로, 그래프, 동적 계획법
정답자
아직 제출이 없습니다

문제

Little I has invented an algorithm for finding the minimum cycle in a directed graph with the time complexity of O(n+m)O(n + m), and now he wants to test your skills.

You are given a directed graph with nn vertices and mm edges. Each edge has a positive integer weight. Your task is to find a cycle in the graph such that the sum of edge weights on the cycle is minimized. Output the minimum value of this sum or report if there is no cycle.

Of course, since you may not know the O(n+m)O(n + m) algorithm for finding the minimum cycle, Little I has relaxed the conditions: the input graph is guaranteed to be weakly connected, and m−nm - n won't be very large. A graph is weakly connected if and only if it becomes a connected undirected graph after replacing directed edges with undirected edges.

입력

The first line contains two integers nn and mm (1≤n≤3⋅1051 \le n \le 3 \cdot 10^5, −1≤m−n≤1500-1 \le m - n \le 1500) representing the number of vertices and edges in the graph.

Each of the next mm lines contains three integers u_iu\_i, v_iv\_i, w_iw\_i (1≤u_i,v_i≤n1 \le u\_i, v\_i \le n, 1≤w_i≤1091 \le w\_i \le 10^9) representing a directed edge from u_iu\_i to v_iv\_i with weight w_iw\_i. The graph is guaranteed to be weakly connected.

출력

Print a line with a single integer: the length of the minimum cycle in the graph, or −1-1 if there is no cycle.

힌트

In the first example, the minimum cycle is 1→2→4→3→11 \to 2 \to 4 \to 3 \to 1.

예제3

  1. 예제 1

    입력
    4 6
    1 2 1
    4 3 3
    4 1 9
    2 4 1
    3 1 2
    3 2 6
    
    예상 출력
    7
    
  2. 예제 2

    입력
    1 0
    
    예상 출력
    -1
    
  3. 예제 3

    입력
    1 1
    1 1 1
    
    예상 출력
    1