Yet Another Shortest Path Query

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

요약
무방향 가중 평면 그래프와 여러 질의가 주어질 때 두 정점 사이의 간선 3개 이하 최단 경로 길이를 구하고, 없으면 -1을 출력한다.
난이도

보통10점 중 5점

유형
그래프, 해시맵, 완전 탐색
정답자
아직 제출이 없습니다

문제

In graph theory, a planar graph is a graph that can be drawn on the plane in such a way that its edges intersect only at their endpoints. In other words, it can be drawn so that no edges cross each other. Such a drawing is called a plane graph or a planar embedding of the graph. A plane graph can be defined as a planar graph with a mapping from every node to a point on the plane, and from every edge to a plane curve on that plane, such that the extreme points of each curve are the points mapped from its end nodes, and all curves are disjoint except for their extreme points.

You will be given an undirected planar graph with nn vertices and mm edges. The vertices are labeled by 1,2,…,n1, 2, \ldots, n. The ii-th edge connects vertices u_iu\_i and v_iv\_i, and its length is w_iw\_i.

You will then be given qq queries. In the ii-th query, you will be given two integers s_is\_i and t_it\_i. Please write a program to figure out the length of the shortest path from vertex s_is\_i to vertex t_it\_i such that the path contains no more than three edges, or determine that there is no such path.

입력

The first line of the input contains two integers nn and mm (2≤n≤1062 \leq n \leq 10^6, 1≤m≤1061 \leq m \leq 10^6) denoting the number of vertices and the number of edges.

In the next mm lines, the ii-th line contains three integers u_iu\_i, v_iv\_i and w_iw\_i (1≤u_i,v_i≤n1 \leq u\_i, v\_i \leq n, u_i≠v_iu\_i \neq v\_i, 1≤w_i≤1081 \leq w\_i \leq 10^8) describing the ii-th edge. It is guaranteed that there is at most one edge between each pair of vertices. It is also guaranteed that the graph is planar.

The next line contains a single integer qq (1≤q≤1061 \leq q \leq 10^6) denoting the number of queries.

In the next qq lines, the ii-th line contains two integers s_is\_i and t_it\_i (1≤s_i,t_i≤n1 \leq s\_i, t\_i \leq n, s_i≠t_is\_i \neq t\_i) describing the ii-th query.

출력

For each query, print a single line containing an integer denoting the length of the shortest path containing at most three edges. If there is no such path, please print "-1" instead.

예제2

  1. 예제 1

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

    입력
    6 4
    1 2 1
    2 3 1
    3 4 1
    4 5 1
    3
    1 4
    1 5
    1 6
    
    예상 출력
    3
    -1
    -1