Under construction

Still being built. Things may change

Shortest Path Query

Time limit2sMemory limit1024 MB

Summary
Given a DAG whose edges are black or white, answer queries for the shortest distance from vertex 1 to x when black edges cost a and white edges cost b.
Level

Hard8 of 10

Topics
Shortest path, Dynamic programming, Graph
Solved
No attempts yet

Problem

You are given a directed acyclic graph with nn vertices, labeled 1,2,…,n1, 2, \ldots, n. The graph has mm edges, and each edge is either black or white. Every vertex is reachable from vertex 11.

You are given qq queries. In the ii-th query, you get three integers aia_i, bib_i, and xix_i. Give each black edge length aia_i and each white edge length bib_i. Find the length of the shortest path from vertex 11 to vertex xix_i.

Input

The first line contains two integers nn and mm (1≤n≤500001 \leq n \leq 50000, 1≤m≤1000001 \leq m \leq 100000), the number of vertices and edges.

Each of the next mm lines contains uiu_i, viv_i, and cic_i, describing a directed edge from vertex uiu_i to vertex viv_i (1≤ui<vi≤n1 \leq u_i < v_i \leq n, vi−ui≤1000v_i - u_i \leq 1000, 0≤ci≤10 \leq c_i \leq 1). The edge is black if ci=0c_i = 0 and white if ci=1c_i = 1.

The next line contains qq (1≤q≤500001 \leq q \leq 50000), the number of queries. Each of the next qq lines contains aia_i, bib_i, and xix_i (1≤ai,bi≤100001 \leq a_i, b_i \leq 10000, 1≤xi≤n1 \leq x_i \leq n).

Output

For each query, print one line containing the length of the shortest path from vertex 11 to vertex xix_i.

Examples1

  1. Example 1

    Input
    4 4
    1 2 0
    1 3 1
    2 4 0
    3 4 1
    3
    3 5 2
    3 2 4
    2 3 4
    
    Expected output
    3
    4
    4