Under construction

Still being built. Things may change

Mana Collection

Time limit5sMemory limit1024 MB

Summary
Given a directed graph of mana pools with collection rates, find the most mana collectable in s seconds while ending at pool e, for each query.
Level

Hard9 of 10

Topics
Dynamic programming, Bit manipulation, Shortest path, Divide and conquer
Solved
No attempts yet

Problem

Bessie has recently taken an interest in magic and needs to collect mana for a very important spell. Bessie has NN (1≤N≤181\le N\le 18) mana pools, the iith of which accumulates mim_i mana per second (1≤mi≤1081\le m_i\le 10^8). The pools are linked by a collection of MM (0≤M≤N(N−1)0\le M\le N(N-1)) directed edges (ai,bi,ti)(a_i,b_i,t_i), meaning that she can travel from aia_i to bib_i in tit_i seconds (1≤ai,bi≤N1\le a_i, b_i\le N, ai≠bia_i\neq b_i, 1≤ti≤1091\le t_i\le 10^9). Whenever Bessie is present at a pool, she can collect all the mana stored there, emptying it. At time 00, all mana pools are empty, and Bessie can start at any pool.

Answer QQ (1≤Q≤2⋅1051\le Q\le 2\cdot 10^5) queries. Each query gives two integers ss and ee (1≤s≤1091\le s\le 10^9, 1≤e≤N1\le e\le N). For each query, find the maximum amount of mana Bessie can collect in ss seconds if she must be at mana pool ee at the end of the ssth second.

Input

The first line contains NN and MM.

The next line contains m1,m2,…,mNm_1, m_2, \dots, m_N.

The next MM lines each contain aia_i, bib_i, tit_i. No ordered pair (ai,bi)(a_i,b_i) appears more than once.

The next line contains QQ.

The next QQ lines each contain two integers ss and ee.

Output

Print QQ lines, one for each query.

Examples2

  1. Example 1

    Input
    2 1
    1 10
    1 2 10
    4
    5 1
    5 2
    100 1
    100 2
    
    Expected output
    5
    50
    100
    1090
    
  2. Example 2

    Input
    4 8
    50000000 100000000 20000000 70000000
    1 2 20
    2 1 50
    2 3 90
    1 3 40
    3 1 10
    4 1 25
    1 4 5
    4 3 70
    3
    8 3
    1000000000 1
    500000 4
    
    Expected output
    160000000
    239999988050000000
    119992550000000