PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FW0000089. Thiết kế đồ thị và truy vấn đường ngắn (Design Graph With Shortest Path Calculator)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Thiết kế đồ thị và truy vấn đường ngắn (Design Graph With Shortest Path Calculator)

Design Graph With Shortest Path Calculator

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A directed positive-weighted graph with 0-based vertices supports sequential operations 1 u v w (add a directed edge) and 2 s t (query current shortest distance, or -1 when unreachable). Parallel edges may be added.

Input

First n,mn,m, then mm directed edges uvw‘,thenu v w`, then q$ operations of type 1 or 2; vertices are 0-based.

Output

Print a distance or -1 for every type-2 operation.

Subtasks

  • Subtask 1 (40 points): 2≤n≤7, 1≤q≤72\le n\le7,\ 1\le q\le7. 0≤m≤10000\le m\le1000, 1≤w≤1091\le w\le10^9, 0≤u,v,s,t<n0\le u,v,s,t<n; các cung có hướng.

  • Subtask 2 (60 points): 2≤n≤30, 1≤q≤152\le n\le30,\ 1\le q\le15. 0≤m≤10000\le m\le1000, 1≤w≤1091\le w\le10^9, 0≤u,v,s,t<n0\le u,v,s,t<n; các cung có hướng.

Examples

Input

3 2
0 1 2
1 2 3
4
2 0 2
1 0 2 1
2 0 2
2 2 0

Output

5
1
-1

Explanation

The first 0→2 query costs 5 via vertex 1. Adding a direct edge of cost 1 improves the answer to 1; vertex 2 still cannot reach vertex 0.