Problem:
不思議なボタン
あなたは，町外れにあるダンジョンでコインを稼ぐことにした．このダンジョンには
N
個の部屋が存在し，
1
から
N
までの番号がつけられている．また，ダンジョン内には「コインボタン」「脱出ボタン」「ワープボタン」と呼ばれる不思議なボタンが存在する．それぞれのボタンの詳細は次の通りである．
コインボタンは各部屋にちょうど
1
個存在する．コインボタンは何回でも押すことができ，そのたびにコインが
1
枚手に入る．
脱出ボタンは各部屋にちょうど
1
個存在する．脱出ボタンを押すとあなたはただちにダンジョンから脱出し，この冒険を終了する．
ワープボタンは合計で
M
個存在する．このうち
i
個目のワープボタンは部屋
a
i
に存在し，押すことであなたは部屋
b
i
にワープし，さらにコインが
c
i
枚手に入る．ただし，
a
i
< b
i
および
1 ≤ c
i
≤ 3
を満たす．なお，ワープボタンが 1 つの部屋に複数ある場合や，ワープボタンのまったく無い部屋が存在する場合もある．
なお，ボタンを押す以外の方法で部屋を移動することはできず，複数のボタンを同時に押すこともできない．また，いずれのボタンも互いに区別可能である．
あなたはこのダンジョンを
Q
回冒険した．あなたの記憶が正しければ，
j
回目の冒険は部屋
1
から始まり，最後に部屋
d
j
にある脱出ボタンを押し，コインの合計獲得枚数はちょうど
e
j
枚だったはずである．
Q
回の冒険それぞれについて，そのようなボタンの押し方が何通りあるかを求めよ．答えは大きくなる可能性があるので，
10
9
+7
すなわち
1000000007
で割った余りを求めよ．
ただし，2 通りの「ボタンの押し方」が異なるとは，ボタンを押した合計回数が異なるか，またはある整数
k
が存在し，
k
回目に押したボタンが異なることを指す．
なお，もしかしたらあなたの記憶は間違っており，そのようなボタンの押し方は存在しないかもしれない．その場合には
0
を出力せよ．
Input
入力は複数のデータセットからなる． 各データセットは次の形式で表される．
N
M
a
1
b
1
c
1
a
2
b
2
c
2
...
a
M
b
M
c
M
Q
d
1
e
1
d
2
e
2
...
d
Q
e
Q
データセットの 1 行目には，部屋の数を表す整数
N
と，ワープボタンの数を表す整数
M
が与えられ，
1 ≤ N, M ≤ 2 000
を満たす．続く
M
行にはワープボタンの情報が与えられる．
M
行のうち
i
行目には，
i
番目のワープボタンの存在する部屋番号
a
i
，ワープ先の部屋番号
b
i
および手に入るコインの枚数
c
i
が与えられ，
1 ≤ a
i
< b
i
≤ N
および
1 ≤ c
i
≤ 3
を満たす．
M+2
行目には冒険の回数を表す整数
Q
が与えられ，
1 ≤ Q ≤ 2 000
を満たす．続く
Q
行にはあなたの記憶にある冒険の情報が与えられる．
Q
行のうち
j
行目には，
j
番目の冒険であなたが脱出ボタンを押した部屋番号
d
j
およびコインの獲得枚数
e
j
が与えられ，
1 ≤ d
j
≤ N
および
1 ≤ e
j
≤ 10
9
を満たす．
入力の終わりは，2 個のゼロだけからなる行で表される．全データセットの総数は 50 を超えない．
Output
各データセットについて出力は
Q
行からなる．このうち
j
行目には，部屋
1
から始まり，最後に部屋
d
j
にある脱出ボタンを押し，コインの合計獲得枚数がちょうど
e
j
枚であるようなボタンの押し方の総数を，
10
9
+7
で割った余りを出力せよ．
Sample Input
4 9
1 2 1
1 2 2
1 3 1
1 3 2
1 3 3
2 3 1
2 3 2
1 4 1
3 4 2
8
1 5
2 5
3 5
4 5
1 1234567
2 1234567
3 1234567
4 1234567
4 8
1 2 1
1 2 1
1 2 3
3 4 3
1 4 2
2 4 1
2 4 3
2 4 3
8
1 3
2 6
3 8
4 12
1 31415926
2 53589793
3 23846
4 26433832
0 0
Output for the Sample Input
1
9
37
21
1
2469133
307629943
60012504
1
16
0
424
1
160769377
0
43581113

Submitted solutions:

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
* @brief template
*/

template <unsigned mod = 1000000007> struct fp {
    unsigned v;
    static constexpr int get_mod() {
        return mod;
    }
    constexpr unsigned inv() const {
        assert(v != 0);
        int x = v, y = mod, p = 1, q = 0, t = 0, tmp = 0;
        while (y > 0) {
            t = x / y;
            x -= t * y, p -= t * q;
            tmp = x, x = y, y = tmp;
            tmp = p, p = q, q = tmp;
        }
        if (p < 0)
            p += mod;
        return p;
    }
    constexpr fp(ll x = 0) : v(x >= 0 ? x % mod : (mod - (-x) % mod) % mod) {}
    fp operator-() const {
        return fp() - *this;
    }
    fp pow(ull t) {
        fp res = 1, b = *this;
        while (t) {
            if (t & 1)
                res *= b;
            b *= b;
            t >>= 1;
        }
        return res;
    }
    fp &operator+=(const fp &x) {
        if ((v += x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator-=(const fp &x) {
        if ((v += mod - x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator*=(const fp &x) {
        v = ull(v) * x.v % mod;
        return *this;
    }
    fp &operator/=(const fp &x) {
        v = ull(v) * x.inv() % mod;
        return *this;
    }
    fp operator+(const fp &x) const {
        return fp(*this) += x;
    }
    fp operator-(const fp &x) const {
        return fp(*this) -= x;
    }
    fp operator*(const fp &x) const {
        return fp(*this) *= x;
    }
    fp operator/(const fp &x) const {
        return fp(*this) /= x;
    }
    bool operator==(const fp &x) const {
        return v == x.v;
    }
    bool operator!=(const fp &x) const {
        return v != x.v;
    }
    friend istream &operator>>(istream &is, fp &x) {
        return is >> x.v;
    }
    friend ostream &operator<<(ostream &os, const fp &x) {
        return os << x.v;
    }
};

// template <unsigned mod> void rd(fp<mod> &x) {
//     fastio::rd(x.v);
// }
// template <unsigned mod> void wt(fp<mod> x) {
//     fastio::wt(x.v);
// }

template <typename T> T Inv(ll n) {
    static const int md = T::get_mod();
    static vector<T> buf({0, 1});
    assert(n > 0);
    n %= md;
    while (SZ(buf) <= n) {
        int k = SZ(buf), q = (md + k - 1) / k;
        buf.push_back(buf[k * q - md] * q);
    }
    return buf[n];
}

template <typename T> T Fact(ll n, bool inv = 0) {
    static const int md = T::get_mod();
    static vector<T> buf({1, 1}), ibuf({1, 1});
    assert(n >= 0 and n < md);
    while (SZ(buf) <= n) {
        buf.push_back(buf.back() * SZ(buf));
        ibuf.push_back(ibuf.back() * Inv<T>(SZ(ibuf)));
    }
    return inv ? ibuf[n] : buf[n];
}

template <typename T> T nPr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nCr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(r, inv ^ 1) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nHr(int n, int r, bool inv = 0) {
    return nCr<T>(n + r - 1, r, inv);
}

/**
 * @brief Modint
 */

using Fp = fp<>;

int main() {
    cin.tie(0);
    ios_base::sync_with_stdio(false);
while(1) {
    int N, M;
    cin >> N >> M;
    if (N == 0) return 0;
    vector<int> A(M), B(M), C(M);
    vector<vector<pair<int,int>>> G(N);
    rep(i,0,M) {
        cin >> A[i] >> B[i] >> C[i];
        A[i]--, B[i]--;
        G[A[i]].push_back({B[i],C[i]});
    }
    int L = N * 3;
    vector<vector<Fp>> DP(N, vector<Fp>(L+1, 0));
    DP[0][0] = 1;
    rep(i,0,N) {
        rep(j,0,L) DP[i][j+1] += DP[i][j];
        for (auto [b,c] : G[i]) {
            rep(j,0,L+1) {
                if (j+c <= L) DP[b][j+c] += DP[i][j];
            }
        }
    }
    int Q;
    cin >> Q;
    while(Q--) {
        int D, E;
        cin >> D >> E;
        D--;
        if (E <= L) cout << DP[D][E] << '\n';
        else {
            E -= N*2;
            vector<Fp> Small(N+1), Big(N+1);
            Small[0] = 1;
            rep(i,0,N) Small[i+1] = Small[i] * (E-N+i);
            Big[0] = 1;
            rep(i,0,N) Big[i+1] = Big[i] * (E-i);
            Fp ANS = 0;
            rep(i,0,N+1) {
                ANS += DP[D][i+N*2] * Big[i] * Small[N-i] * Fact<Fp>(i,1) * Fact<Fp>(N-i,1) * ((N-i)%2==0 ? 1 : -1);
            }
            cout << ANS << '\n';
        }
    }
}
}
accuracy: 1
time_ms: 1760
memory_kb: 50108
final_rank: 1

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 2 "cp-library/src/number/modint.hpp"
struct modinfo { uint mod, root, isprime; };
template < modinfo const &ref >
struct modint {
    static constexpr uint const &mod = ref.mod;
    static constexpr uint const &root = ref.root;
    static constexpr uint const &isprime = ref.isprime;
    uint v = 0;
    constexpr modint& s(uint v) { this->v = v < mod ? v : v - mod; return *this; }
    constexpr modint(ll v = 0) { s(v % mod + mod); }
    modint operator-() const { return modint() - *this; }
    modint& operator+=(const modint& rhs) { return s(v + rhs.v); }
    modint& operator-=(const modint& rhs) { return s(v + mod - rhs.v); }
    modint& operator*=(const modint& rhs) { v = ull(v) * rhs.v % mod; return *this; }
    modint& operator/=(const modint& rhs) { return *this *= inv(rhs); }
    modint operator+(const modint& rhs) const { return modint(*this) += rhs; }
    modint operator-(const modint& rhs) const { return modint(*this) -= rhs; }
    modint operator*(const modint& rhs) const { return modint(*this) *= rhs; }
    modint operator/(const modint& rhs) const { return modint(*this) /= rhs; }
    friend modint pow(modint x, ll n) { modint res(1); while(n > 0) { if(n & 1) res *= x; x *= x; n >>= 1; } return res; }
    friend modint inv(modint v) {
        if(isprime) {
            return pow(v, mod - 2);
        } else {
            ll a = v.v, b = modint::mod, x = 1, y = 0, t;
            while(b > 0) { t = a / b; swap(a -= t * b, b); swap(x -= t * y, y); }
            return modint(x);
        }
    }
    friend modint operator+(int x, const modint& y) { return modint(x) + y; }
    friend modint operator-(int x, const modint& y) { return modint(x) - y; }
    friend modint operator*(int x, const modint& y) { return modint(x) * y; }
    friend modint operator/(int x, const modint& y) { return modint(x) / y; }
    friend istream& operator>>(istream& is, modint& m) { ll x; is >> x; m = modint(x); return is; }
    friend ostream& operator<<(ostream& os, const modint& m) { return os << m.v; }
    bool operator==(const modint& r) const { return v == r.v; }
    bool operator!=(const modint& r) const { return v != r.v; }
    static uint get_mod() { return mod; }
    static int is_prime() { return isprime; }
};
constexpr modinfo base998244353 { 998244353, 3, 1 };
constexpr modinfo base1000000007 { 1000000007, 0, 1 };
using mint998244353 = modint< base998244353 >;
using mint1000000007 = modint< base1000000007 >;
#line 3 "cp-library/src/number/binom_mod.hpp"

template < class mint >
mint fact(int n) {
    assert(0 <= n);
    assert(mint::is_prime());
    static const uint mod = mint::get_mod();
    static std::vector<mint> data = {1, 1};
    while(int(data.size()) <= n) {
        int i = data.size();
        data.push_back(data.back() * i);
    }
    return data[n];
}

template < class mint >
mint inv(int n) {
    assert(0 <= n);
    assert(mint::is_prime());
    static const uint mod = mint::get_mod();
    static std::vector<mint> data = {1, 1};
    while(int(data.size()) <= n) {
        int i = data.size();
        data.push_back(- data[mod % i] * (mod / i));
    }
    return data[n];
}

template < class mint >
mint fact_inv(int n) {
    assert(0 <= n);
    assert(mint::is_prime());
    static const uint mod = mint::get_mod();
    static std::vector<mint> data = {1, 1};
    while(int(data.size()) <= n) {
        int i = data.size();
        data.push_back(data.back() * inv<mint>(i));
    }
    return data[n];
}

template < class mint >
mint comb(int n, int k) {
    if(k < 0 or n < k) return 0;
    return fact<mint>(n) * fact_inv<mint>(k) * fact_inv<mint>(n - k);
}

template < class mint >
mint perm(int n, int k) {
    return fact<mint>(n) * fact_inv<mint>(n - k);
}

template < class mint >
mint homo(int n, int k) {
    return comb<mint>(n + k - 1, k);
}

template < class mint > struct power {
    mint a;
    std::vector<mint> data = {1};
    power() {}
    power(const mint a) : a(a) {}
    // a^n
    mint get(const int n) {
        assert(0 <= n);
        while(int(data.size()) <= n)
            data.push_back(data.back() * a);
        return data[n];
    }
};
#line 3 "cp-library/src/number/ntt.hpp"
namespace ntt {

template < class mint >
void trans(vector<mint>& v, bool is_inv) {
    if(v.empty()) return;
    int n = v.size();
    uint mod = mint::mod, root = mint::root;
    static bool first = true;
    static vector<ll> vbw(30), vibw(30);
    if(first) {
        first = false;
        for(int k : rep(30)) {
            vbw[k] = pow(mint(root), (mod - 1) >> (k + 1)).v;
            vibw[k] = inv(mint(vbw[k])).v;
        }
    }
    for(int i = 0, j = 1; j < n - 1; j++) {
        for(int k = n >> 1; k > (i ^= k); k >>= 1);
        if(i > j) swap(v[i], v[j]);
    }
    for(int k = 0, t = 2; t <= n; ++k, t <<= 1) {
        mint bw = (is_inv ? vibw[k] : vbw[k]);
        for (int i = 0; i < n; i += t) {
            mint w = 1;
            for (int j = 0; j < t / 2; ++j) {
                int j1 = i + j, j2 = i + j + t/2;
                mint c1 = v[j1], c2 = v[j2] * w;
                v[j1] = c1 + c2;
                v[j2] = c1 - c2;
                w *= bw;
            }
        }
    }
    if(is_inv) {
        mint iv = inv(mint(n));
        for(int i : rep(n)) v[i] *= iv;
    }
}
template < class mint > void ntt(vector<mint>& v) { trans(v, false); }
template < class mint > void intt(vector<mint>& v) { trans(v, true); }

// for garner
constexpr modinfo base0 { 754974721, 11, 1};
constexpr modinfo base1 { 167772161,  3, 1};
constexpr modinfo base2 { 469762049,  3, 1};
using mint0 = modint< base0 >;
using mint1 = modint< base1 >;
using mint2 = modint< base2 >;
static const mint1 imod0  =  95869806; // MOD0^-1 mod MOD1
static const mint2 imod1  = 104391568; // MOD1^^1 mod MOD2
static const mint2 imod01 = 187290749; // imod1 / MOD0;

template < class T >
vector< T > naive(const vector< T >& a, const vector< T >& b) {
    if(a.empty() || b.empty()) return {};
    int n = a.size(), m = b.size();
    vector< T > c(n + m - 1);
    for(int i : rep(n)) for(int j : rep(m)) c[i + j] += a[i] * b[j];
    return c;
}

template < class mint >
vector<mint> mul(const vector<mint>& a, const vector<mint>& b) {
    if(a.empty() || b.empty()) return {};
    int n = a.size(), m = b.size();
    if(min(n, m) < 30) return naive(a, b);
    uint mod = mint::mod;

    int sz = [&]() {
        int n2 = 1, m2 = 1;
        while(n2 < n) n2 <<= 1;
        while(m2 < m) m2 <<= 1;
        return max(n2, m2) << 1;
    }();

    if(mod == 998244353) {
        vector<mint> a2(sz, 0), b2(sz, 0), c(sz, 0);
        for(int i : rep(n)) a2[i] = a[i];
        for(int i : rep(m)) b2[i] = b[i];
        ntt(a2), ntt(b2);
        for(int i : rep(sz)) c[i] = a2[i] * b2[i];
        intt(c);
        c.resize(n + m - 1);
        return c;
    }

    vector<mint0> a0(sz, 0), b0(sz, 0), c0(sz, 0);
    vector<mint1> a1(sz, 0), b1(sz, 0), c1(sz, 0);
    vector<mint2> a2(sz, 0), b2(sz, 0), c2(sz, 0);
    for(int i : rep(n)) a0[i].v = a1[i].v = a2[i].v = a[i].v;
    for(int i : rep(m)) b0[i].v = b1[i].v = b2[i].v = b[i].v;
    ntt(a0), ntt(b0), ntt(a1), ntt(b1), ntt(a2), ntt(b2);
    for(int i : rep(sz)) {
        c0[i] = a0[i] * b0[i];
        c1[i] = a1[i] * b1[i];
        c2[i] = a2[i] * b2[i];
    }
    intt(c0), intt(c1), intt(c2);
    
    vector<mint> c(n + m - 1);
    static const mint mod0 = mint0::mod, mod01 = mod0 * mint1::mod;
    for(int i : rep(n + m - 1)) {
        ll y0 = c0[i].v;
        ll y1 = (imod0 * (c1[i] - y0)).v;
        ll y2 = (imod01 * (c2[i] - y0) - imod1 * y1).v;
        c[i] = mod01 * y2 + mod0 * y1 + y0;
    }
    return c;
}

} // namespace ntt
#line 3 "cp-library/src/utility/random.hpp"

namespace randnum {

static uint seed;
static std::mt19937 mt;
struct gen_seed {
    gen_seed() {
        seed = std::random_device()();
        mt = std::mt19937(seed);
    }
} gs;

// [L, R)
template < class T >
T gen_int(T L, T R) {
    return std::uniform_int_distribution< T >(L, R - 1)(mt);
}

template < class T >
T get_real(T L, T R) {
    return std::uniform_real_distribution< T >(L, R)(mt);
}

}
#line 4 "cp-library/src/number/modfunc.hpp"

u64 modpow64(u64 a, u64 n, u64 mod) {
    a %= mod;
    u64 res = 1;
    while(n > 0) {
        if(n % 2 == 1) res = i128(res) * a % mod;
        a = i128(a) * a % mod;
        n /= 2;
    }
    return res;
}

u64 modpow(u64 a, u64 n, u64 mod) {
    a %= mod;
    u64 res = 1;
    while(n > 0) {
        if(n % 2 == 1) res = res * a % mod;
        a = a * a % mod;
        n /= 2;
    }
    return res;
}

long long modinv(long long a, long long m) {
    long long b = m, u = 1, v = 0;
    while (b) {
        long long t = a / b;
        a -= t * b; swap(a, b);
        u -= t * v; swap(u, v);
    }
    u %= m; 
    if (u < 0) u += m;
    return u;
}

// solve x^2 = a (mod p)
// return x
// or No Solution (-1)
i32 modsqrt(i32 a, i32 p) {
    if(p == 2) return a;
    a %= p;
    if(a == 0) return 0;
    if(modpow(a, (p - 1) / 2, p) != 1) return -1;
    i32 q = p - 1, m = 0; while(q % 2 == 0) q /= 2, m++;
    i32 z; do { z = randnum::gen_int<i32>(1, p); } while(modpow(z, (p - 1) / 2, p) != p - 1);
    i64 c = modpow(z, q, p), t = modpow(a, q, p), r = modpow(a, (q + 1) / 2, p);
    while(m > 1) {
        if(modpow(t, 1 << (m - 2), p) != 1) r = r * c % p, t = t * (c * c % p) % p;
        c = c * c % p;
        m -= 1;
    }
    return r;
}
#line 5 "cp-library/src/number/fps.hpp"

class undefined {};
template < class mint > struct fps : std::vector<mint> {
    using std::vector<mint>::vector;
    fps(const std::vector<mint>& f) : std::vector<mint>(f) {}
    int size() const { return int(std::vector<mint>::size()); }
    void ups(int s) { if(size() < s) this->resize(s, 0); }
    fps low(int s) const {
        return fps(this->begin(), this->begin() + min(this->size(), s));
    }
    fps rev() const {
        return fps(this->rbegin(), this->rend());
    }
    fps operator-() const {
        fps g = *this;
        for(int i : rep(g.size())) g[i] = -g[i];
        return g;
    }
    fps operator+(const mint& v) const { return fps(*this) += v; }
    fps operator-(const mint& v) const { return fps(*this) -= v; }
    fps operator*(const mint& v) const { return fps(*this) *= v; }
    fps operator/(const mint& v) const { return fps(*this) /= v; }
    fps operator+(const fps& r) const { return fps(*this) += r; }
    fps operator-(const fps& r) const { return fps(*this) -= r; }
    fps operator*(const fps& r) const { return fps(*this) *= r; }
    fps operator/(const fps& r) const { return fps(*this) /= r; }
    fps operator<<(int s) const { return fps(*this) <<= s; }
    fps operator>>(int s) const { return fps(*this) >>= s; }
    fps& operator+=(const fps& r) { ups(r.size()); for(int i : rep(r.size())) (*this)[i] += r[i]; return *this; }
    fps& operator-=(const fps& r) { ups(r.size()); for(int i : rep(r.size())) (*this)[i] -= r[i]; return *this; }
    fps& operator*=(const fps& r) { return *this = ntt::mul(*this, r); } // ntt
    fps& operator/=(const fps& r) { return *this *= inv(r); }
    template < class T > fps& operator+=(T v) { ups(1); (*this)[0] += v; return *this; }
    template < class T > fps& operator-=(T v) { ups(1); (*this)[0] -= v; return *this; }
    template < class T > fps& operator*=(T v) { for(auto &x : *this) x *= v; return *this; }
    template < class T > fps& operator/=(T v) { assert(v != T(0)); return *this *= mint(1) / v; }

    fps& operator<<=(int s) {
        fps g(s, 0);
        g.insert(g.end(), this->begin(), this->end());
        return *this = g;
    }
    fps& operator>>=(int s) {
        return *this = {this->begin() + s, this->end()};
    }
    friend fps differential(const fps& f) {
        int n = f.size();
        fps g(n - 1);
        for(int i : rep(1, n)) g[i - 1] = f[i] * i;
        return g;
    }
    friend fps integral_(const fps& f) { // std と衝突
        int n = f.size();
        fps g(n + 1, 0);
        for(int i : rep(0, n)) g[i + 1] = f[i] / (i + 1);
        return g;
    }
    friend fps inv(const fps& f, int deg) {
        assert(f[0] != 0);
        fps g = {mint(1) / f[0]};
        for(int i = 1; i < deg; i <<= 1) {
            g = (g + g - g * g * f.low(i << 1)).low(i << 1);
        }
        g.resize(deg);
        return g;
    }
    friend fps log(const fps& f, int deg) {
        assert(f[0] == 1);
        fps g = integral_((differential(f) * inv(f, deg)));
        g.resize(deg);
        return g;
    }
    friend fps exp(const fps& f, int deg) {
        assert(f[0] == 0);
        fps g = {1};
        for(int i = 1; i < deg; i <<= 1) {
            g = g * (f.low(i << 1) - log(g, i << 1) + 1).low(i << 1);
        }
        g.resize(deg);
        return g;
    }
    friend fps pow(const fps& f, ll n, int deg) {
        if(n == 0) {
            fps g(deg, 0);
            g[0] = 1;
            return g;
        }
        int i = 0;
        while(i < f.size() and f[i] == 0) i++;
        if(i == f.size() or i128(i) * n >= deg) return fps(deg, 0);
        mint k = f[i];
        fps g = exp(log((f >> i) / k, deg) * n, deg) * pow(k, n) << (i * n);
        g.resize(deg);
        return g;
    }
    friend fps sqrt(const fps& f, int deg) {
        int n = f.size(), d = n;
        for(int i : revrep(0, n)) if(f[i] != 0) d = i;
        if(d == n) return f;
        if(d % 2 == 1) throw undefined();
        mint y = f[d], x = modsqrt(y.v, mint::get_mod());
        if(x * x != y) throw undefined();
        mint c = mint(1) / y;
        fps g(n - d);
        for(int i : rep(n - d)) g[i] = f[d + i] * c;
        
        assert(g[0] == 1);
        mint inv2 = mint(1) / 2;
        fps h = {1};
        for(int i = 1; i < deg; i <<= 1) {
            h = (h + g.low(i << 1) * inv(h, i << 1)).low(i << 1);
            for(mint& a : h) a *= inv2;
        }
        h.resize(deg);

        for(int i : rep(deg)) h[i] *= x;
        for(int i : revrep(deg)) h[i] = (i >= d / 2 ? h[i - d / 2] : 0);
        return h;
    }

    friend fps inv(const fps& f) { return inv(f, f.size()); }
    friend fps log(const fps& f) { return log(f, f.size()); }
    friend fps exp(const fps& f) { return exp(f, f.size()); }
    friend fps pow(const fps& f, ll n) { return pow(f, n, f.size()); }
    friend fps sqrt(const fps& f) { return sqrt(f, f.size()); }

    fps operator() (const fps<mint>& g) {
        fps<mint>& f = *this;
        assert(f.size() == g.size());
        int n = f.size(), k = ceil(sqrt(n));

        vector< fps<mint> > bs(k + 1);
        bs[0] = {1};
        for(int i : rep(k)) bs[i + 1] = (bs[i] * g).low(n);

        vector< fps<mint> > gs(k + 1);
        gs[0] = {1};
        for(int i : rep(k)) gs[i + 1] = (gs[i] * bs[k]).low(n);

        fps<mint> h(n);
        for(int i : rep(0, n, k)) {
            fps<mint> c;
            for(int j : rep(i, min(i + k, n))) c += bs[j - i] * f[j];
            h += (c * gs[i / k]).low(n);
        }
        return h;
    }
};

#line 2 "cp-library/src/data_structure/sliding_window_aggregation.hpp"

template < class monoid >
struct swag_queue {
  public:
    using T = typename monoid::set;
    class node {
      public:
        T value, sum;
        node() : value(monoid::id()), sum(monoid::id()) {}
        node(const T& value, const T& sum) : value(value), sum(sum) {}
    };
    std::stack<node> front_stack, back_stack;

  public:
    swag_queue() { front_stack.push(node()), back_stack.push(node()); }
    int size() const {
        return (int(front_stack.size()) - 1) + (int(back_stack.size()) - 1);
    }
    bool empty() const {
        return size() == 0;
    }
    T fold() const {
        return monoid::op(front_stack.top().sum, back_stack.top().sum);
    }
    void push(const T& x) {
        back_stack.push(node(x, monoid::op(back_stack.top().sum, x)));
    }
    void pop() {
        assert(not empty());
        if(front_stack.size() == 1) {
            while(back_stack.size() > 1) {
                front_stack.push(node(back_stack.top().value, monoid::op(back_stack.top().value, front_stack.top().sum)));
                back_stack.pop();
            }
        }
        front_stack.pop();
    }
};

template < class monoid >
struct swag_deque {
  private:
    using T = typename monoid::set;
    class node {
      public:
        T value, sum;
        node() : value(monoid::id()), sum(monoid::id()) {}
        node(const T& value, const T& sum) : value(value), sum(sum) {}
    };
    std::stack<node> front_stack, back_stack;

  public:
    swag_deque() { front_stack.push(node()), back_stack.push(node()); }
    int size() const { return (int(front_stack.size()) - 1) + (int(back_stack.size()) - 1); }
    bool empty() const { return size() == 0; }

    T fold() const { return monoid::op(front_stack.top().sum, back_stack.top().sum); }
    void push_front(const T& x) { push(front_stack, x, 1); }
    void push_back (const T& x) { push( back_stack, x, 0); }
    void pop_front() { assert(not empty()); if(front_stack.size() == 1) amortize( back_stack, front_stack, 1); front_stack.pop(); }
    void pop_back () { assert(not empty()); if( back_stack.size() == 1) amortize(front_stack,  back_stack, 0);  back_stack.pop(); }

  private:
    void push(std::stack<node>& st, const T& x, int f) {
        st.push(node(x, f ? monoid::op(x, st.top().sum) : monoid::op(st.top().sum, x)));
    }
    void amortize(std::stack<node>& from, std::stack<node>& to, int f) {
        std::stack< T > st;
        while(st.size() < from.size() - 2) st.push(from.top().value), from.pop();
        while(from.size() > 1) push(to, from.top().value, f), from.pop();
        while(not st.empty()) push(from, st.top(), 1 - f), st.pop();
        printer::flush();
    }
};
#line 7 "A.cpp"

template < class T > class prod_monoid {
  public:
    using set = T;
    static constexpr T op(const T &l, const T &r) { return l * r; }
    static constexpr T id() { return T(1); }
};


void solve(int N, int M) {
    vector<vector<pair<int,int>>> G(N);
    for(int _ : rep(M)) {
        int a = in(), b = in(), c = in(); a--, b--;
        G[b].push_back({a, c});
    }

    using mint = mint1000000007;
    vector<fps<mint>> f(N);
    f[0] = vector<mint>(N);
    for(int i : rep(N)) {
        f[0][i] = comb<mint>(N - 1, i) * (i % 2 == 0 ? +1 : -1);
    }
    for(int to : rep(1, N)) {
        for(auto [from, c] : G[to]) f[to] += f[from] << c;
        const int n = f[to].size();
        for(int i : rep(n - 1)) f[to][i + 1] += f[to][i];
    }

    int Q = in();
    for(int _ : rep(Q)) {
        int v = in(), e = in(); v--;
        mint ans = 0;
        const int n = f[v].size();
        swag_queue<prod_monoid<mint>> swag;
        for(int k = N - 1; k >= 1; k--) swag.push(e + k);
        for(int i : rep(n)) {
            const int j = e - i;
            if(0 <= j) {
                ans += f[v][i] * fact_inv<mint>(N - 1) * swag.fold();
            }
            swag.push(j);
            swag.pop();
        }
        print(ans);
    }
}

int main() {
    while(true) {
        int N = in(), M = in(); if(make_pair(N, M) == make_pair(0, 0)) return 0;
        solve(N, M);
    }
}
accuracy: 1
time_ms: 5160
memory_kb: 42480
final_rank: 2

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, b) for (ll i = ll(a); i < ll(b); i++)
#define all(p) begin(p),end(p)

const ll mod = 1000000007;
struct mm {
   ll x;
   mm(ll x_ = 0) : x(x_ % mod) {
      if(x < 0) x += mod;
   }
   friend mm operator+(mm a, mm b) { return a.x + b.x; }
   friend mm operator-(mm a, mm b) { return a.x - b.x; }
   friend mm operator*(mm a, mm b) { return a.x * b.x; }
   friend mm operator/(mm a, mm b) { return a * b.inv(); }
   // 4 行コピペ  Alt + Shift + クリックで複数カーソル
   friend mm& operator+=(mm& a, mm b) { return a = a.x + b.x; }
   friend mm& operator-=(mm& a, mm b) { return a = a.x - b.x; }
   friend mm& operator*=(mm& a, mm b) { return a = a.x * b.x; }
   friend mm& operator/=(mm& a, mm b) { return a = a * b.inv(); }
   mm inv() const { return pow(mod - 2); }
   mm pow(ll b) const {
      mm a = *this, c = 1;
      while(b) {
         if(b & 1) c *= a;
         a *= a;
         b >>= 1;
      }
      return c;
   }
};


void solve(ll N, ll M){
    using mint = mm;
    vector<mint> fact(N + 1, 1), fact_inv(N + 1, 1);
    rep(i, 1, N + 1) fact[i] = fact[i - 1] * i;
    fact_inv[N] = fact[N].inv();
    for (ll i = N; i > 0; i--) fact_inv[i - 1] = fact_inv[i] * i;
    // return Bi(a, b)
    auto comb = [&](ll a, ll b) -> mint {
        if (a < b || b < 0) return 0;
        return fact[a] * fact_inv[a - b] * fact_inv[b];
    };
    ll L = N * 3 + 10;
    vector<vector<pair<int, int>>> G(N);
    rep(i, 0, M){
        int a, b, c;
        cin >> a >> b >> c;
        a--, b--;
        G[a].push_back({b, c});
    }
    // [x ^ e] dp[i] / (1 - x) ^ N
    vector dp(N, vector<mint>(L));
    rep(i, 0, N + 1) dp[0][i] = comb(N, i) * (i & 1 ? -1 : 1);
    rep(i, 0, N){
        int len = (N + 2 * i);
        rep(j, 0, len) dp[i][j + 1] += dp[i][j];
        for (auto e : G[i]){
            rep(j, 0, len) dp[e.first][e.second + j] += dp[i][j];
        }
    }
    int Q;
    cin >> Q;
    while (Q--){
        ll d, e;
        cin >> d >> e;
        d--;
        mint ans = 0;
        mint tmp = fact_inv[N - 1];
        vector<mint> sum(N + d * 2, 1);
        for (int j = N + d * 2 - 2; j >= 0; j--){
            if (e - j + N - 1 > 0){
                sum[j] = sum[j + 1] * (e - j + N - 1);
            }
        }
        tmp /= sum[N - 1];
        rep(j, 0, N + d * 2){
            if (e < j) break;
            ans += dp[d][j] * tmp * sum[j];
            // tmp *= (e - j)
            tmp *= (e - j);
        }
        cout << ans.x << "\n";
    }
}
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    ll N, M;
    while (cin >> N >> M, N) solve(N, M);
}
accuracy: 1
time_ms: 2990
memory_kb: 97256
final_rank: 8

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, b) for (ll i = ll(a); i < ll(b); i++)
#define all(p) begin(p),end(p)

const ll mod = 1000000007;
struct mm {
   ll x;
   mm(ll x_ = 0) : x(x_ % mod) {
      if(x < 0) x += mod;
   }
   friend mm operator+(mm a, mm b) { return a.x + b.x; }
   friend mm operator-(mm a, mm b) { return a.x - b.x; }
   friend mm operator*(mm a, mm b) { return a.x * b.x; }
   friend mm operator/(mm a, mm b) { return a * b.inv(); }
   // 4 行コピペ  Alt + Shift + クリックで複数カーソル
   friend mm& operator+=(mm& a, mm b) { return a = a.x + b.x; }
   friend mm& operator-=(mm& a, mm b) { return a = a.x - b.x; }
   friend mm& operator*=(mm& a, mm b) { return a = a.x * b.x; }
   friend mm& operator/=(mm& a, mm b) { return a = a * b.inv(); }
   mm inv() const { return pow(mod - 2); }
   mm pow(ll b) const {
      mm a = *this, c = 1;
      while(b) {
         if(b & 1) c *= a;
         a *= a;
         b >>= 1;
      }
      return c;
   }
};


void solve(ll N, ll M){
    using mint = mm;
    vector<mint> fact(N + 1, 1), fact_inv(N + 1, 1);
    rep(i, 1, N + 1) fact[i] = fact[i - 1] * i;
    fact_inv[N] = fact[N].inv();
    for (ll i = N; i > 0; i--) fact_inv[i - 1] = fact_inv[i] * i;
    // return Bi(a, b)
    auto comb = [&](ll a, ll b) -> mint {
        if (a < b || b < 0) return 0;
        return fact[a] * fact_inv[a - b] * fact_inv[b];
    };
    ll L = N * 3 + 10;
    vector<vector<pair<int, int>>> G(N);
    rep(i, 0, M){
        int a, b, c;
        cin >> a >> b >> c;
        a--, b--;
        G[a].push_back({b, c});
    }
    // [x ^ e] dp[i] / (1 - x) ^ N
    vector dp(N, vector<mint>(L));
    rep(i, 0, N + 1) dp[0][i] = comb(N, i) * (i & 1 ? -1 : 1);
    rep(i, 0, N){
        int len = (N + 2 * i);
        rep(j, 0, len) dp[i][j + 1] += dp[i][j];
        for (auto e : G[i]){
            rep(j, 0, len) dp[e.first][e.second + j] += dp[i][j];
        }
    }
    int Q;
    cin >> Q;
    while (Q--){
        ll d, e;
        cin >> d >> e;
        d--;
        mint ans = 0;
        mint tmp = fact_inv[N - 1];
        vector<mint> sum(N + d * 2, 1);
        for (int j = N + d * 2 - 2; j >= 0; j--){
            if (e - j + N - 1 > 0){
                sum[j] = sum[j + 1] * (e - j + N - 1);
            }
        }
        tmp /= sum[N - 1];
        rep(j, 0, N + d * 2){
            if (e < j) break;
            ans += dp[d][j] * tmp * sum[j];
            // tmp *= (e - j)
            tmp *= (e - j);
        }
        cout << ans.x << "\n";
    }
}
int main(){
    ll N, M;
    while (cin >> N >> M, N) solve(N, M);
}
accuracy: 1
time_ms: 3050
memory_kb: 97144
final_rank: 9

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, b) for (ll i = ll(a); i < ll(b); i++)
#define all(p) begin(p),end(p)

const ll mod = 1000000007;
struct mm {
   ll x;
   mm(ll x_ = 0) : x(x_ % mod) {
      if(x < 0) x += mod;
   }
   friend mm operator+(mm a, mm b) { return a.x + b.x; }
   friend mm operator-(mm a, mm b) { return a.x - b.x; }
   friend mm operator*(mm a, mm b) { return a.x * b.x; }
   friend mm operator/(mm a, mm b) { return a * b.inv(); }
   // 4 行コピペ  Alt + Shift + クリックで複数カーソル
   friend mm& operator+=(mm& a, mm b) { return a = a.x + b.x; }
   friend mm& operator-=(mm& a, mm b) { return a = a.x - b.x; }
   friend mm& operator*=(mm& a, mm b) { return a = a.x * b.x; }
   friend mm& operator/=(mm& a, mm b) { return a = a * b.inv(); }
   mm inv() const { return pow(mod - 2); }
   mm pow(ll b) const {
      mm a = *this, c = 1;
      while(b) {
         if(b & 1) c *= a;
         a *= a;
         b >>= 1;
      }
      return c;
   }
};


void solve(ll N, ll M){
    using mint = mm;
    ll L = N * 3 + 10;
    vector<mint> fact(L + 1, 1), fact_inv(L + 1, 1);
    rep(i, 1, L + 1) fact[i] = fact[i - 1] * i;
    fact_inv[L] = fact[L].inv();
    for (ll i = L; i > 0; i--) fact_inv[i - 1] = fact_inv[i] * i;
    // return Bi(a, b)
    auto comb = [&](ll a, ll b) -> mint {
        if (a < b || b < 0) return 0;
        mint res = 1;
        rep(i, 0, b) res *= a - i;
        return res * fact_inv[b];
    };
    vector<vector<pair<int, int>>> G(N);
    rep(i, 0, M){
        int a, b, c;
        cin >> a >> b >> c;
        a--, b--;
        G[a].push_back({b, c});
    }
    // [x ^ e] dp[i] / (1 - x) ^ N
    vector dp(N, vector<mint>(L));
    rep(i, 0, N + 1) dp[0][i] = comb(N, i) * (i & 1 ? -1 : 1);
    rep(i, 0, N){
        int len = (N + 2 * i);
        rep(j, 0, len) dp[i][j + 1] += dp[i][j];
        for (auto e : G[i]){
            rep(j, 0, len) dp[e.first][e.second + j] += dp[i][j];
        }
    }
    int Q;
    cin >> Q;
    while (Q--){
        ll d, e;
        cin >> d >> e;
        d--;
        mint ans = 0;
        mint tmp = fact_inv[N - 1];
        vector<mint> sum(N + d * 2, 1);
        for (int j = N + d * 2 - 2; j >= 0; j--){
            if (e - j + N - 1 > 0){
                sum[j] = sum[j + 1] * (e - j + N - 1);
            }
        }
        tmp /= sum[N - 1];
        rep(j, 0, N + d * 2){
            if (e < j) break;
            ans += dp[d][j] * tmp * sum[j];
            // tmp *= (e - j)
            tmp *= (e - j);
        }
        cout << ans.x << "\n";
    }
}
int main(){
    ll N, M;
    while (cin >> N >> M, N) solve(N, M);
}
accuracy: 1
time_ms: 3150
memory_kb: 97340
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
#define all(A) A.begin(),A.end()
#define rep(i, n) for (int i = 0; i < (int) (n); i++)

const ll mod=1e9+7;

vll factinv(5000,1);

ll inva(ll n){
    ll m=mod-2;
    ll res=1;
    while(m>0){
        if(m%2){
            res=(res*n)%mod;
        }
        n=(n*n)%mod;
        m/=2;
    }
    return res;
}

void solve(ll N,ll M){
    vector<vector<pair<ll,ll>>> G(N);
    rep(i,M){
        ll A,B,C;
        cin>>A>>B>>C;
        B--;A--;
        G[A].push_back({B,C});
    }
    vector<vll> DP(N,vll(3*N+1,0));
    DP[0][0]=1;
    rep(i,N){
        rep(j,3*N)DP[i][j+1]=(DP[i][j]+DP[i][j+1])%mod;
        rep(j,3*N)for(auto [v,w]:G[i]){
            if(j+w<=3*N)DP[v][w+j]=(DP[i][j]+DP[v][w+j])%mod;
        }
    }

    ll Q;
    cin>>Q;
    rep(q,Q){
        ll D,E;
        cin>>D>>E;
        D--;
        if(E<=3*N){
            cout<<DP[D][E]<<endl;
            continue;
        }
        else{
            ll an=0;
            E-=2*N;
            ll mul=1;
            rep(n,N+1){
                mul=(mul*(E-n))%mod;
            }
            rep(n,N+1){
                ll res=DP[D][2*N+n];
                res*=mul;
                res%=mod;
                res*=inva(E-n);
                res%=mod;
                res*=factinv[n];
                res%=mod;
                res*=factinv[N-n];
                res%=mod;
                if((N-n)%2!=0)res*=-1;
                res%=mod;
                an+=res;
            }
            an%=mod;
            if(an<0)an+=mod;
            cout<<an<<endl;
        }


        // cout<<"MADA"<<endl;
    }
}

int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    rep(i,5000){
        factinv[i+1]=(factinv[i]*inva(i+1))%mod;
    }

    ll N,M;
    while(cin>>N>>M){
        if(N==0)return 0;
        solve(N,M);
    }
    


}
accuracy: 1
time_ms: 7070
memory_kb: 97188
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
#define all(A) A.begin(),A.end()
#define rep(i, n) for (int i = 0; i < (int) (n); i++)

const ll mod=1e9+7;

vll factinv(5000,1);

ll inva(ll n){
    ll m=mod-2;
    ll res=1;
    while(m>0){
        if(m%2){
            res=(res*n)%mod;
        }
        n=(n*n)%mod;
        m/=2;
    }
    return res;
}

void solve(ll N,ll M){
    vector<vector<pair<ll,ll>>> G(N);
    rep(i,M){
        ll A,B,C;
        cin>>A>>B>>C;
        B--;A--;
        G[A].push_back({B,C});
    }
    vector<vll> DP(N,vll(4*N+1,0));
    DP[0][0]=1;
    rep(i,N){
        rep(j,4*N)DP[i][j+1]=(DP[i][j]+DP[i][j+1])%mod;
        rep(j,4*N)for(auto [v,w]:G[i]){
            if(j+w<=4*N)DP[v][w+j]=(DP[i][j]+DP[v][w+j])%mod;
        }
    }

    ll Q;
    cin>>Q;
    rep(q,Q){
        ll D,E;
        cin>>D>>E;
        D--;
        if(E<=4*N){
            cout<<DP[D][E]<<endl;
            continue;
        }
        else{
            ll an=0;
            E-=3*N;
            ll mul=1;
            rep(n,N+1){
                mul=(mul*(E-n))%mod;
            }
            rep(n,N+1){
                ll res=DP[D][3*N+n];
                res*=mul;
                res%=mod;
                res*=inva(E-n);
                res%=mod;
                res*=factinv[n];
                res%=mod;
                res*=factinv[N-n];
                res%=mod;
                if((N-n)%2!=0)res*=-1;
                res%=mod;
                an+=res;
            }
            an%=mod;
            if(an<0)an+=mod;
            cout<<an<<endl;
        }


        // cout<<"MADA"<<endl;
    }
}

int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    rep(i,5000){
        factinv[i+1]=(factinv[i]*inva(i+1))%mod;
    }

    ll N,M;
    while(cin>>N>>M){
        if(N==0)return 0;
        solve(N,M);
    }
    


}
accuracy: 1
time_ms: 7560
memory_kb: 128336
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, n) for (int i = int(s); i < int(n); i++)
#define rrep(i, s, n) for (int i = int(n) - 1; i >= s; i--)

template<ll m> struct modint{
	using mint = modint;
	ll a;
	modint(ll x = 0): a((x%m +m)%m){}
	static ll mod(){return m;}
	ll& val(){return a;}
	mint pow(ll n){
		mint res = 1;
		mint x = a;
		while(n){
			if (n&1) res *= x;
			x *= x;
			n >>= 1;
		}
		return res;
	}
	mint inv(){
		return pow(m-2);
	}
	mint& operator+=(const mint rhs){
		a += rhs.a;
		if (a >= m) a-= m;
		return *this;
	}
	mint& operator-=(const mint rhs){
		if (a<rhs.a) a+= m;
		a -= rhs.a;
		return *this;
	}
	mint& operator*=(const mint rhs){
		a = a*rhs.a%m;
		return *this;
	}
	mint &operator/=(mint rhs){
		*this *= rhs.inv();
		return *this;
	}
	friend mint operator+(const mint& lhs, const mint& rhs){
		return mint(lhs) += rhs;
	}
	friend mint operator-(const mint& lhs, const mint& rhs){
		return mint(lhs) -= rhs;
	}
	friend mint operator*(const mint& lhs, const mint& rhs){
		return mint(lhs) *= rhs;
	}
	friend mint operator/(const mint& lhs, const mint& rhs){
		return mint(lhs )/= rhs;
	}
	mint operator+() const{
		return *this;
	}
	mint operator-() const{
		return mint() - *this;
	}

};

using modint1000000007 = modint<1'000'000'007>;
using mint = modint1000000007;

struct combination {
    std::vector<mint> fact, inv_fact;
    combination(int n) : fact(n+1, 1), inv_fact(n+1) {
        rep(i,1,n+1) {
            fact[i] = fact[i-1] * i;
        }
        inv_fact[n] = fact[n].inv();
        rrep(i,1,n+1) {
            inv_fact[i-1] = inv_fact[i] * i;
        }
    }

    mint operator()(int n, int k) const {
        if(n < k || k < 0) return 0;
        return fact[n] * inv_fact[n-k] * inv_fact[k];
    } 
} comb(2000000);

void solve(int n, int m){
    vector<vector<pair<int,int>>> ikeru(n, vector<pair<int,int>>(0));

    for (int i=0; i<m; i++){
        int a, b, c; cin >> a >> b >> c;
        a--; b--;
        ikeru[b].push_back(pair(a,c));
    }

    vector<vector<mint>> f(n, vector<mint>(0));
    f[0].resize(n+1);
    for (int i=0; i<=n; i++){
        if (i % 2 == 0){
            f[0][i] = comb(n, i);
        }else{
            f[0][i] = -comb(n, i);
        }
    }

    for (int i=1; i<n; i++){
        int v = 0;
        for (auto[b, c]: ikeru[i]){
            v = max(v, (int)f[b].size() - 1 + c);
        }
        f[i].resize(v);
        for (auto[b, c]: ikeru[i]){
            for (int j=0; j<(int)f[b].size(); j++){
                if (c+j>=v) break;
                f[i][j+c] += f[b][j];
            }
        }
        for (int j=0; j<v-1; j++){
            f[i][j+1] += f[i][j];
        }
    }

    int q; cin >> q;
    int mod = mint::mod();
    for (int i=0; i<q; i++){
        int x; cin >> x;
        int e; cin >> e;
        x--;
        vector<vector<mint>> lfttable(5, vector<mint>(n));
        vector<vector<mint>> rgttable(5, vector<mint>(n));
        for (int k=0; k<5; k++){
            mint a = 1;
            for (int j=n-1; j>=0; j--){
                a *= mint(e+n-j-k*n);
                rgttable[k][j] = a;
            }
        }
        for (int k=0; k<5; k++){
            mint a = 1;
            for (int j=0; j<n; j++){
                a *= mint(e+n-j-k*n);
                lfttable[k][j] = a;
            }
        }
        
        mint ans = 0;
        for (int j=0; j<(int)f[x].size(); j++){
            if (e+n-j-n < 0) break;
            if (j%n==0){
                ans += comb.inv_fact[n] * f[x][j] * rgttable[j/n][0];
            }else{
                ans += comb.inv_fact[n] * f[x][j] * rgttable[j/n][j%n] * lfttable[j/n+1][j%n-1];
            }
        }
        cout << ans.val() << "\n";
    }
}

int main() {
    while(true){
        int n, m; cin >> n >> m;
        if (n == 0) break;
        solve(n, m);
    }
}
accuracy: 1
time_ms: 4090
memory_kb: 73088
final_rank: 4

code_snippet: #include <bits/stdc++.h>

using namespace std;
#define rep(i, s, n) for (int i = int(s); i < int(n); i++)
#define rrep(i, s, n) for (int i = int(n) - 1; i >= s; i--)
#define all(v) v.begin(), v.end()

using ll = long long;
using ld = long double;
using ull = unsigned long long;

template <class T> bool chmin(T &a, T b) {
    if (a <= b) return false;
    a = b;
    return true;
}

template <class T> bool chmax(T &a, T b) {
    if (a >= b) return false;
    a = b;
    return true;
}

    template<ll m> struct modint{
        using mint = modint;
        ll a;
        modint(ll x = 0): a((x%m +m)%m){}
        static ll mod(){return m;}
        ll& val(){return a;}
        mint pow(ll n){
            mint res = 1;
            mint x = a;
            while(n){
                if (n&1) res *= x;
                x *= x;
                n >>= 1;
            }
            return res;
        }
        mint inv(){
            return pow(m-2);
        }
        mint& operator+=(const mint rhs){
            a += rhs.a;
            if (a >= m) a-= m;
            return *this;
        }
        mint& operator-=(const mint rhs){
            if (a<rhs.a) a+= m;
            a -= rhs.a;
            return *this;
        }
        mint& operator*=(const mint rhs){
            a = a*rhs.a%m;
            return *this;
        }
        mint &operator/=(mint rhs){
            *this *= rhs.inv();
            return *this;
        }
        friend mint operator+(const mint& lhs, const mint& rhs){
            return mint(lhs) += rhs;
        }
        friend mint operator-(const mint& lhs, const mint& rhs){
            return mint(lhs) -= rhs;
        }
        friend mint operator*(const mint& lhs, const mint& rhs){
            return mint(lhs) *= rhs;
        }
        friend mint operator/(const mint& lhs, const mint& rhs){
            return mint(lhs )/= rhs;
        }
        mint operator+() const{
            return *this;
        }
        mint operator-() const{
            return mint() - *this;
        }

    };

using modint1000000007 = modint<1'000'000'007>;
using mint = modint1000000007;

struct combination {
    std::vector<mint> fact, inv_fact;
    combination(int n) : fact(n+1, 1), inv_fact(n+1) {
        rep(i,1,n+1) {
            fact[i] = fact[i-1] * i;
        }
        inv_fact[n] = fact[n].inv();
        rrep(i,1,n+1) {
            inv_fact[i-1] = inv_fact[i] * i;
        }
    }

    mint operator()(int n, int k) const {
        if(n < k || k < 0) return 0;
        return fact[n] * inv_fact[n-k] * inv_fact[k];
    } 
} comb(2000000);

void solve(int n, int m){
    vector<vector<pair<int,int>>> ikeru(n, vector<pair<int,int>>(0));
    for (int i=0; i<m; i++){
        int a, b, c; cin >> a >> b >> c;
        a--; b--;
        ikeru[b].push_back(pair(a,c));
    }
    vector<vector<mint>> f(n, vector<mint>(0));
    f[0].resize(n+1);
    for (int i=0; i<=n; i++){
        if (i % 2 == 0){
            f[0][i] = comb(n, i);
        }else{
            f[0][i] = -comb(n, i);
        }
        //cout << comb(n, i).val() << endl;
    }

    for (int i=1; i<n; i++){
        int v = 0;
        for (auto[b, c]: ikeru[i]){
            v = max(v, (int)f[b].size() - 1 + c);
        }
        f[i].resize(v);
        for (auto[b, c]: ikeru[i]){
            for (int j=0; j<(int)f[b].size(); j++){
                if (c+j>=v) break;
                f[i][j+c] += f[b][j];
            }
        }
        for (int j=0; j<v-1; j++){
            f[i][j+1] += f[i][j];
        }
    }

    int q; cin >> q;
    int mod = mint::mod();
    for (int i=0; i<q; i++){
        int x; cin >> x;
        int e; cin >> e;
        x--;

        vector<vector<mint>> lfttable(5, vector<mint>(n));
        vector<vector<mint>> rgttable(5, vector<mint>(n));
        for (int k=0; k<5; k++){
            mint a = 1;
            for (int j=n-1; j>=0; j--){
                a *= mint(e+n-j-k*n);
                rgttable[k][j] = a;
            }
        }
        for (int k=0; k<5; k++){
            mint a = 1;
            for (int j=0; j<n; j++){
                a *= mint(e+n-j-k*n);
                lfttable[k][j] = a;
            }
        }
        
        mint ans = 0;
        for (int j=0; j<(int)f[x].size(); j++){
            if (e+n-j-n < 0) break;
            if (j%n==0){
                ans += comb.inv_fact[n] * f[x][j] * rgttable[j/n][0];
            }else{
                ans += comb.inv_fact[n] * f[x][j] * rgttable[j/n][j%n] * lfttable[j/n+1][j%n-1];
            }
        }
        cout << ans.val() << "\n";
    }
}

int main() {
    while(true){
        int n, m; cin >> n >> m;
        if (n == 0) break;
        solve(n, m);
    }
}
accuracy: 1
time_ms: 4080
memory_kb: 72992
final_rank: 3

code_snippet: #include<deque>
#include<queue>
#include<vector>
#include<algorithm>
#include<iostream>
#include<set>
#include<cmath>
#include<tuple>
#include<string>
#include<chrono>
#include<functional>
#include<iterator>
#include<random>
#include<unordered_set>
#include<array>
#include<map>
#include<iomanip>
#include<assert.h>
#include<list>
#include<bitset>
#include<stack>
#include<memory>
#include<numeric>
#include<complex>
using namespace std;
using namespace std::chrono;
typedef long long int llint;
typedef long double lldo;
#define mp make_pair
#define mt make_tuple
#define pub push_back
#define puf push_front
#define pob pop_back
#define pof pop_front
#define fir first
#define sec second
#define res resize
#define ins insert
#define era erase

/*cout<<fixed<<setprecision(20);cin.tie(0);ios::sync_with_stdio(false);*/
const llint mod=1000000007;
const llint inf=2.19e15+1;
const long double pai=3.141592653589793238462643383279502884197;
const long double eps=1e-10;
template <class T,class U>bool chmin(T& a,U b){if(a>b){a=b;return true;}return false;}
template <class T,class U>bool chmax(T& a,U b){if(a<b){a=b;return true;}return false;}
llint gcd(llint a,llint b){if(a%b==0){return b;}else return gcd(b,a%b);}
llint lcm(llint a,llint b){if(a==0){return b;}return a/gcd(a,b)*b;}
template<class T> void SO(T& ve){sort(ve.begin(),ve.end());}
template<class T> void REV(T& ve){reverse(ve.begin(),ve.end());}
template<class T>llint LBI(const vector<T>&ar,T in){return lower_bound(ar.begin(),ar.end(),in)-ar.begin();}
template<class T>llint UBI(const vector<T>&ar,T in){return upper_bound(ar.begin(),ar.end(),in)-ar.begin();}
#include <algorithm>
#include <utility>
#include <type_traits>
#include <cstdint>
//永夜作
#define mint mint_base
class mint_base;
//mint_base_base型用の累乗関数
constexpr mint_base m_pow(mint_base x, int64_t n)noexcept;
//mod計算を自動で行う整数テンプレートクラス
class mint_base
{
public:
	constexpr mint_base operator+(const mint_base &other)const noexcept
	{auto v = *this;return v += other;}
	constexpr mint_base operator-(const mint_base &other)const noexcept
	{auto v = *this;return v -= other;}
	constexpr mint_base operator*(const mint_base &other)const noexcept
	{auto v = *this;return v *= other;}
	constexpr auto operator/(const mint_base &other)const noexcept
	{auto v = *this;return v /= other;}
	constexpr mint_base & operator+=(const mint_base &other) noexcept
	{a += other.a;if (mod <= a) { a -= mod; };return *this;}
	constexpr mint_base & operator-=(const mint_base &other) noexcept
	{if (a >= other.a) {a -= other.a;}else {a = (a + mod) - other.a;}return *this;}
	constexpr mint_base & operator*=(const mint_base &other) noexcept
	{a *= other.a;a %= mod;return *this;}
	constexpr mint_base & operator/=(const mint_base &other) noexcept
	{return *this *= ~other;}
	constexpr mint_base operator+()const noexcept { return *this; }
	constexpr mint_base operator-()const noexcept
	{return{ mod - a, mod_value_tag{} };}
	constexpr mint_base & operator++() noexcept
	{if (mod <= ++a) { a = 0; };return *this;}
	constexpr mint_base & operator--() noexcept
	{if (a <= 0) { a = mod; };--a;return *this;}
	constexpr mint_base operator++(int) noexcept
	{auto tmp = *this;++*this;return tmp;}
	constexpr mint_base operator--(int) noexcept
	{auto tmp = *this;--*this;return tmp;}
	constexpr mint_base operator~()const noexcept
	{return m_pow(*this, mod-2);}
	constexpr mint_base & operator=(const mint_base &other) noexcept
	{a=other.a;return *this;}
	constexpr explicit operator int64_t()const noexcept
	{return a;}
	constexpr explicit operator int()const noexcept
	{return a;}
	constexpr explicit operator unsigned()const noexcept
	{return (unsigned)a;}
	static constexpr int64_t getmod() noexcept
	{return mod;}
	constexpr mint_base(int64_t a_) noexcept :a(a_ % mod) {}
	constexpr mint_base()noexcept : a(0) {}
	struct mod_value_tag {};
	constexpr mint_base(int64_t a_, mod_value_tag) :a(a_) {}
private:
	int64_t a;
};

//mint_base型用の累乗関数
constexpr mint_base m_pow(mint_base x,int64_t n)noexcept
{
	mint_base res = 1;
	while(n>0){
		if(n&1){res*=x;}
		x*=x;
		n>>=1;
	}
	return res;
}
//mint_baseの階乗計算
//0からxまでの階乗を返す
//O(x)時間が必要
vector<mint_base> fla;//階乗が入る
void fla_set(mint_base x)
{
	fla.resize(((int64_t)x)+1);
	fla[0] = 1;
	for (int64_t i = 1; i <= (int64_t)x;i++){fla[i]=fla[i-1]*i;}
}
vector<mint_base> gya;//~fla[i] が入る

//O(x+log mod)で求める O(xlogmod)より速い
void fla_gya_set(mint_base x)
{
	fla_set(x);
	gya.resize(((int64_t)x)+1);
	gya[(int64_t)x]=~fla[(int64_t)x];
	for(int64_t i =(int64_t)x;i>0;i--){gya[i-1]=gya[i]*i;}
}

//mint_base型のstreamへの出力
std::ostream& operator<<(std::ostream& os, mint_base i)
{os<<(int64_t)i;return os;}
//mint_base型のstreamからの入力
std::istream& operator >> (std::istream& is, mint_base& i)
{int64_t tmp;is>>tmp;i=tmp;return is;}


int main(void){
	cout<<fixed<<setprecision(20);cin.tie(0);ios::sync_with_stdio(false);
	static mint tako[2000][6001];
	while(-1){
		int n,m,i,j;cin>>n>>m;
		if(n==0){return 0;}
		vector<vector<pair<int,int>>>go(n);
		for(i=0;i<m;i++){
			int a,b,c;cin>>a>>b>>c;
			a--;b--;
			go[a].pub(mp(b,c));
		}
		vector<int>dim(n);
		vector<int>mai(n);
		
		for(i=0;i<n;i++){
			for(j=0;j<=6000;j++){tako[i][j]=0;}
		}
		tako[0][4000]=1;
		for(i=0;i<n;i++){
			for(auto it:go[i]){
				int ter=it.fir;
				int c=it.sec;
				chmax(dim[ter],dim[i]+1);
				chmax(mai[ter],mai[i]+c-1);
				for(j=4000-mai[i];j<=4000+dim[i];j++){
					tako[ter][j+1]+=tako[i][j];
					if(c==1){tako[ter][j]-=tako[i][j];}
					else if(c==2){
						tako[ter][j]-=tako[i][j]*2;
						tako[ter][j-1]+=tako[i][j];
					}else if(c==3){
						tako[ter][j]-=tako[i][j]*3;
						tako[ter][j-1]+=tako[i][j]*3;
						tako[ter][j-2]-=tako[i][j];
					}
				}
			}
		}
		int Q;cin>>Q;
		while(Q--){
			int d;llint e;
			cin>>d>>e;
			d--;
			mint ans=0,kake=1;
			for(j=0;j<=dim[d];j++){
				ans+=kake*tako[d][j+4000];
				kake*=(e+j+1);
				kake/=(j+1);
			}
			//cerr<<ans<<endl;
			
			kake=1;
			bool zero=false;
			if(mai[d]+5>=e){
				ans-=tako[d][4000];
				for(j=0;j>=-mai[d];j--){
					if(!zero){
						ans+=kake*tako[d][j+4000];
					}
					if(e+j!=0){kake/=(mint)(mod+e+j);}
					else{zero=false;}
					if(j!=0){kake*=(mint)(mod+j);}
					else{zero=true;}
				}
			}
			cout<<ans<<endl;
		}
	}
	return 0;
}
/*
3 2
1 2 3
2 3 3
7
3 1
3 2
3 3
3 4
3 5
3 6
3 7
0 0
*/
accuracy: 1
time_ms: 6220
memory_kb: 97264
final_rank: 16

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}


template<typename T,T MOD = 1000000007>
struct Mint{
  static constexpr T mod = MOD;
  T v;
  Mint():v(0){}
  Mint(signed v):v(v){}
  Mint(long long t){v=t%MOD;if(v<0) v+=MOD;}

  Mint pow(long long k){
    Mint res(1),tmp(v);
    while(k){
      if(k&1) res*=tmp;
      tmp*=tmp;
      k>>=1;
    }
    return res;
  }

  static Mint add_identity(){return Mint(0);}
  static Mint mul_identity(){return Mint(1);}

  Mint inv(){return pow(MOD-2);}

  Mint& operator+=(Mint a){v+=a.v;if(v>=MOD)v-=MOD;return *this;}
  Mint& operator-=(Mint a){v+=MOD-a.v;if(v>=MOD)v-=MOD;return *this;}
  Mint& operator*=(Mint a){v=1LL*v*a.v%MOD;return *this;}
  Mint& operator/=(Mint a){return (*this)*=a.inv();}

  Mint operator+(Mint a) const{return Mint(v)+=a;}
  Mint operator-(Mint a) const{return Mint(v)-=a;}
  Mint operator*(Mint a) const{return Mint(v)*=a;}
  Mint operator/(Mint a) const{return Mint(v)/=a;}

  Mint operator-() const{return v?Mint(MOD-v):Mint(v);}

  bool operator==(const Mint a)const{return v==a.v;}
  bool operator!=(const Mint a)const{return v!=a.v;}
  bool operator <(const Mint a)const{return v <a.v;}

  static Mint comb(long long n,int k){
    Mint num(1),dom(1);
    for(int i=0;i<k;i++){
      num*=Mint(n-i);
      dom*=Mint(i+1);
    }
    return num/dom;
  }
};
template<typename T,T MOD> constexpr T Mint<T, MOD>::mod;
template<typename T,T MOD>
ostream& operator<<(ostream &os,Mint<T, MOD> m){os<<m.v;return os;}


template<typename M>
M lagrange_interpolation(vector<M> &ys,M t){
  int n=ys.size()-1;
  if(t.v<=n) return ys[t.v];

  vector<M> dp(n+1,1),pd(n+1,1);
  for(int i=0;i<n;i++) dp[i+1]=dp[i]*(t-M(i));
  for(int i=n;i>0;i--) pd[i-1]=pd[i]*(t-M(i));

  vector<M> fact(n+1,1),finv(n+1,1);
  for(int i=1;i<=n;i++) fact[i]=fact[i-1]*M(i);
  finv[n]=M(1)/fact[n];
  for(int i=n;i>=1;i--) finv[i-1]=finv[i]*M(i);

  M res(0);
  for(int i=0;i<=n;i++){
    M tmp=ys[i]*dp[i]*pd[i]*finv[i]*finv[n-i];
    if((n-i)&1) res-=tmp;
    else res+=tmp;
  }
  return res;
}

//INSERT ABOVE HERE
using M = Mint<int>;
const int MAX = 6060;
M dp[2020][MAX]={};
M ad[2020][MAX]={};
signed main(){
  int n,m;
  while(cin>>n>>m,n||m){
    vector<int> as(m),bs(m),cs(m);
    vector< vector<int> > G(n+1);
    for(int i=0;i<m;i++){
      cin>>as[i]>>bs[i]>>cs[i];
      G[as[i]].emplace_back(i);
    }
    as.emplace_back(0);
    bs.emplace_back(1);
    cs.emplace_back(0);
    G[0].emplace_back(m);

    dp[0][0]=M(1);
    for(int v=0;v<=n;v++){
      for(int j=0;j<MAX;j++){
        if(j) ad[v][j]+=ad[v][j-1];
        dp[v][j]+=ad[v][j];
      }

      for(int i:G[v])
        for(int j=0;j+cs[i]<MAX;j++)
          ad[bs[i]][j+cs[i]]+=dp[as[i]][j];
    }

    int q;
    cin>>q;
    for(int i=0;i<q;i++){
      int d,e;
      cin>>d>>e;
      vector<M> ys(dp[d]+n+n,dp[d]+n+n+n+1);
      if(e<n+n+n) cout<<dp[d][e]<<"\n";
      else cout<<lagrange_interpolation(ys,M(e-n-n))<<"\n";
    }

    for(int v=0;v<=n;v++)
      for(int j=0;j<MAX;j++)
        dp[v][j]=ad[v][j]=M(0);
  }
  cout<<flush;
  return 0;
}
accuracy: 1
time_ms: 2790
memory_kb: 99204
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T, class U> using Pa = pair<T, U>;
template <class T> using vec = vector<T>;
template <class T> using vvec = vector<vec<T>>;

constexpr ll mod = 1e9+7;
struct mint {
    ll x;
    mint(ll x=0):x((x%mod+mod)%mod){}
    
    friend ostream &operator<<(ostream& os,const mint& a){
        return os << a.x;
    }

    friend istream &operator>>(istream& is,mint& a){
        ll t;
        is >> t;
        a = mint(t);
        return (is);
    }

    mint& operator+=(const mint a) {
        if ((x += a.x) >= mod) x -= mod;
        return *this;
    }
    mint& operator-=(const mint a) {
        if ((x += mod-a.x) >= mod) x -= mod;
        return *this;
    }
    mint& operator*=(const mint a) {
        (x *= a.x) %= mod;
        return *this;
    }
    mint operator+(const mint a) const {
        mint res(*this);
        return res+=a;
    }
    mint operator-(const mint a) const {
        mint res(*this);
        return res-=a;
    }
    mint operator*(const mint a) const {
        mint res(*this);
        return res*=a;
    }
    mint pow(ll t) const {
        if (!t) return 1;
        mint a = pow(t>>1);
        a *= a;
        if (t&1) a *= *this;
        return a;
    }
    // for prime mod
    mint inv() const {
        return pow(mod-2);
    }
    mint& operator/=(const mint a) {
        return (*this) *= a.inv();
    }
    mint operator/(const mint a) const {
        mint res(*this);
        return res/=a;
    }
};

class combination{
private:
    vec<mint> fact,inv,finv;
public:
    combination(int N){
        fact = inv = finv = vec<mint>(N+1);
        fact[0] = fact[1] = 1;
        inv[0] = inv[1] = 1;
        finv[0] = finv[1] = 1;
        for(ll i=2;i<=N;i++){
            fact[i] = fact[i-1]*i;
            inv[i] = (mint) mod - inv[mod%i]*(mod/i);
            finv[i] = finv[i-1]*inv[i];
        }
    }
    mint f(int i){
        return fact[i];
    }

    mint fiv(int i){
        return finv[i];
    }
    
    mint comb(int n,int k){
        if(n<k) return 0;
        if(n<0 || k<0) return 0;
        return fact[n]*finv[k]*finv[n-k];
    }
    mint hcomb(int n,int k){
        if(n==0 && k==0) return 1;
        return comb(n+k-1,k);
    }
};

mint lagrange_polynomial(const vec<mint>& Y,ll t){
    ll N = Y.size()-1;
    combination comb(N);
    if(t<=N) return Y[t];
    mint res = 0;
    vec<mint> dp(N+1,1),pd(N+1,1);
    for(int i=0;i<N;i++) dp[i+1] = dp[i]*(t-i);
    for(int i=N;i>0;i--) pd[i-1] = pd[i]*(t-i);
    for(int i=0;i<=N;i++){
        mint tmp = Y[i]*dp[i]*pd[i]*comb.fiv(i)*comb.fiv(N-i);
        if((N-i)&1) res -= tmp;
        else res += tmp;
    }
    return res;
}

struct edge{
    int to,coin;
};

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N,M;
    while(cin >> N >> M && N){
        vvec<edge> g(N);
        for(int i=0;i<M;i++){
            int a,b,c;
            cin >> a >> b >> c;
            a--; b--;
            g[a].push_back({b,c});
        }
        vvec<mint> dp(N,vec<mint>(3*N+1,0));
        dp[0][0] = 1;
        for(int i=0;i<N;i++) for(int j=0;j<3*N;j++){
            dp[i][j+1] += dp[i][j];
            for(auto& e:g[i]) if(j+e.coin<=3*N){
                dp[e.to][j+e.coin] += dp[i][j];
            }
        }

        auto solve = [&](){
            ll d,e;
            cin >> d >> e;
            d--;
            if(e<=3*N) cout << dp[d][e] << "\n";
            else{
                vec<mint> Y;
                for(int i=2*N;i<=3*N;i++) Y.push_back(dp[d][i]);
                cout << lagrange_polynomial(Y,e-2*N) << "\n";
            }
        };

        int Q;
        cin >> Q;
        while(Q--){
            solve();
        }
    }
}
accuracy: 1
time_ms: 3750
memory_kb: 96976
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}


template<typename T,T MOD = 1000000007>
struct Mint{
  static constexpr T mod = MOD;
  T v;
  Mint():v(0){}
  Mint(signed v):v(v){}
  Mint(long long t){v=t%MOD;if(v<0) v+=MOD;}

  Mint pow(long long k){
    Mint res(1),tmp(v);
    while(k){
      if(k&1) res*=tmp;
      tmp*=tmp;
      k>>=1;
    }
    return res;
  }

  static Mint add_identity(){return Mint(0);}
  static Mint mul_identity(){return Mint(1);}

  Mint inv(){return pow(MOD-2);}

  Mint& operator+=(Mint a){v+=a.v;if(v>=MOD)v-=MOD;return *this;}
  Mint& operator-=(Mint a){v+=MOD-a.v;if(v>=MOD)v-=MOD;return *this;}
  Mint& operator*=(Mint a){v=1LL*v*a.v%MOD;return *this;}
  Mint& operator/=(Mint a){return (*this)*=a.inv();}

  Mint operator+(Mint a) const{return Mint(v)+=a;}
  Mint operator-(Mint a) const{return Mint(v)-=a;}
  Mint operator*(Mint a) const{return Mint(v)*=a;}
  Mint operator/(Mint a) const{return Mint(v)/=a;}

  Mint operator-() const{return v?Mint(MOD-v):Mint(v);}

  bool operator==(const Mint a)const{return v==a.v;}
  bool operator!=(const Mint a)const{return v!=a.v;}
  bool operator <(const Mint a)const{return v <a.v;}

  static Mint comb(long long n,int k){
    Mint num(1),dom(1);
    for(int i=0;i<k;i++){
      num*=Mint(n-i);
      dom*=Mint(i+1);
    }
    return num/dom;
  }
};
template<typename T,T MOD> constexpr T Mint<T, MOD>::mod;
template<typename T,T MOD>
ostream& operator<<(ostream &os,Mint<T, MOD> m){os<<m.v;return os;}


template<typename M>
M lagrange_interpolation(vector<M> &ys,M t){
  int n=ys.size()-1;
  if(t.v<=n) return ys[t.v];

  vector<M> dp(n+1,1),pd(n+1,1);
  for(int i=0;i<n;i++) dp[i+1]=dp[i]*(t-M(i));
  for(int i=n;i>0;i--) pd[i-1]=pd[i]*(t-M(i));

  vector<M> fact(n+1,1),finv(n+1,1);
  for(int i=1;i<=n;i++) fact[i]=fact[i-1]*M(i);
  finv[n]=M(1)/fact[n];
  for(int i=n;i>=1;i--) finv[i-1]=finv[i]*M(i);

  M res(0);
  for(int i=0;i<=n;i++){
    M tmp=ys[i]*dp[i]*pd[i]*finv[i]*finv[n-i];
    if((n-i)&1) res-=tmp;
    else res+=tmp;
  }
  return res;
}

//INSERT ABOVE HERE
using M = Mint<int>;
const int MAX = 6060;
M dp[2020][MAX]={};
M ad[2020][MAX]={};
signed main(){
  int n,m;
  while(cin>>n>>m,n||m){
    vector<int> as(m),bs(m),cs(m);
    vector< vector<int> > G(n+1);
    for(int i=0;i<m;i++){
      cin>>as[i]>>bs[i]>>cs[i];
      G[as[i]].emplace_back(i);
    }
    as.emplace_back(0);
    bs.emplace_back(1);
    cs.emplace_back(0);
    G[0].emplace_back(m);

    dp[0][0]=M(1);
    for(int v=0;v<=n;v++){
      for(int j=0;j<MAX;j++){
        if(j) ad[v][j]+=ad[v][j-1];
        dp[v][j]+=ad[v][j];
      }

      for(int i:G[v])
        for(int j=0;j+cs[i]<MAX;j++)
          ad[bs[i]][j+cs[i]]+=dp[as[i]][j];
    }

    int q;
    cin>>q;
    for(int i=0;i<q;i++){
      int d,e;
      cin>>d>>e;
      vector<M> ys(dp[d]+n+n,dp[d]+n+n+n+1);
      if(e<n+n+n) cout<<dp[d][e]<<"\n";
      else cout<<lagrange_interpolation(ys,M(e-n-n))<<"\n";
    }

    for(int v=0;v<=n;v++)
      for(int j=0;j<MAX;j++)
        dp[v][j]=ad[v][j]=M(0);
  }
  cout<<flush;
  return 0;
}
accuracy: 1
time_ms: 4030
memory_kb: 98848
final_rank: 15

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;



#define SIZE 2005

struct Edge{
	Edge(int arg_to,int arg_value){
		to = arg_to;
		value = arg_value;
	}
	int to,value;
};

ll N,M;
int in_num[SIZE];
ll fact[3*SIZE],inverse_fact[3*SIZE];
ll dp[SIZE][3*SIZE];
ll head[SIZE],tail[SIZE];
vector<Edge> G[SIZE];


ll extgcd(ll a,ll b,ll &x,ll &y){
	ll d = a;
	if(b != 0){
		d = extgcd(b,a%b,y,x);
		y -= (a/b)*x;
	}else{
		x = 1;
		y = 0;
	}
	return d;
}

ll mod_inverse(ll a,ll m){
    ll x,y;
    extgcd(a,m,x,y);
    return (m+x%m)%m;
}


void func(){

	for(int i = 0; i < SIZE; i++){

		G[i].clear();
		in_num[i] = 0;
	}

	int from,to,value;

	for(int loop = 0; loop < M; loop++){

		scanf("%d %d %d",&from,&to,&value);
		from--;
		to--;

		G[from].push_back(Edge(to,value));

		in_num[to]++;
	}

	for(int i = 0; i < N; i++){
		for(int k = 0; k <= 3*N; k++){
			dp[i][k] = 0;
		}
	}

	dp[0][0] = 1;

	queue<int> Q;
	for(int i = 0; i < N; i++){
		if(in_num[i] == 0){
			Q.push(i);
		}
	}

	while(!Q.empty()){

		int node_id = Q.front();
		Q.pop();

		for(int i = 1; i <= 3*N; i++){

			dp[node_id][i] += dp[node_id][i-1];
			dp[node_id][i] %= MOD;

		}

		for(int i = 0; i <= 3*N-1; i++){
			if(dp[node_id][i] == 0)continue;

			for(int k = 0; k < G[node_id].size();k++){

				if(i+G[node_id][k].value > 3*N)continue;

				dp[G[node_id][k].to][i+G[node_id][k].value] += dp[node_id][i];
				dp[G[node_id][k].to][i+G[node_id][k].value] %= MOD;
			}
		}

		for(int k = 0; k < G[node_id].size(); k++){

			in_num[G[node_id][k].to]--;
			if(in_num[G[node_id][k].to] == 0){

				Q.push(G[node_id][k].to);
			}
		}
	}

	int num_query;
	scanf("%d",&num_query);

	int last_node;
	ll total;

	for(int loop = 0; loop < num_query; loop++){

		scanf("%d %lld",&last_node,&total);
		last_node--;

		if(total <= 3*N){

			printf("%lld\n",dp[last_node][total]);
			continue;
		}

		head[0] = 1;
		for(int i = 1; i <= N; i++){

			head[i] = head[i-1]*((total-2*N)-i+1);
			head[i] %= MOD;
		}

		tail[N] = 1;
		for(int i = N-1; i >= 0; i--){

			tail[i] = tail[i+1]*((total-2*N)-i-1);
			tail[i] %= MOD;
		}

		ll ans = 0;

		for(int i = 2*N; i <= 3*N; i++){

			ll tmp = dp[last_node][i];

			tmp *= head[i-2*N];
			tmp %= MOD;

			tmp *= tail[i-2*N];
			tmp %= MOD;

			ll denominator = (inverse_fact[i-2*N]*inverse_fact[3*N-i])%MOD;
			if((3*N-i)%2 == 1){

				denominator *= (-1+MOD);
				denominator %= MOD;
			}

			tmp *= denominator;
			tmp %= MOD;

			ans += tmp;
			ans %= MOD;
		}

		printf("%lld\n",ans);
	}
}

int main(){

	fact[0] = 1;
	for(ll i = 1; i <= 6000; i++){
		fact[i] = i*fact[i-1];
		fact[i] %= MOD;
	}

	inverse_fact[6000] = mod_inverse(fact[6000],MOD);
	for(ll i = 6000; i >= 1; i--){

		inverse_fact[i-1] = inverse_fact[i]*i;
		inverse_fact[i-1]%= MOD;
	}

	while(true){

		scanf("%lld %lld",&N,&M);
		if(N == 0 && M == 0)break;

		func();
	}

	return 0;
}
accuracy: 1
time_ms: 2810
memory_kb: 97556
final_rank: 6

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <queue>
using namespace std;

typedef long long LL;
typedef pair<int,int> pii;

const LL MOD = 1000000007;

const int DEG = 2100;
const int BASE = 4100;

void add(LL &x, LL y){
	x += y;
	if(x >= MOD){ x -= MOD; }
}

LL powmod(LL x, LL y){
	LL a = 1;
	while(y){
		if(y & 1){ a = a * x % MOD; }
		x = x * x % MOD;
		y >>= 1;
	}
	return a;
}

LL invs[DEG + 1];

void solve(int n, int m){
	vector<vector<pii>> G(n);
	for(int i = 0; i < m; ++i){
		int s, t, d;
		cin >> s >> t >> d;
		G[s - 1].emplace_back(t - 1, d);
	}

	vector<vector<LL>> cnts(n, vector<LL>(BASE + DEG + 1));
	cnts[0][0] = 1;
	for(int u = 0; u < n; ++u){
		auto &from = cnts[u];
		for(int i = 0; i < BASE + DEG; ++i){
			add(from[i + 1], from[i]);
		}
		for(const auto &p : G[u]){
			auto &to = cnts[p.first];
			for(int i = 0; i + p.second <= BASE + DEG; ++i){
				add(to[i + p.second], from[i]);
			}
		}
	}

	vector<LL> ltmul(DEG + 2), rtmul(DEG + 2);
	int q;
	cin >> q;
	for(int qnum = 0; qnum < q; ++qnum){
		int e;
		LL t;
		cin >> e >> t;
		--e;

		LL res = 0;
		if(t <= BASE + DEG){
			res = cnts[e][t];
		}
		else{
			LL s = (t - BASE) % MOD;
			ltmul[0] = 1;
			for(int i = 0; i <= DEG; ++i){
				ltmul[i + 1] = ltmul[i] * (s - i) % MOD;
			}
			rtmul.back() = 1;
			for(int i = DEG; i >= 0; --i){
				rtmul[i] = rtmul[i + 1] * (s - i) % MOD;
			}
			for(int i = 0; i <= DEG; ++i){
				LL x = ltmul[i] * rtmul[i + 1] % MOD * invs[i] % MOD;
				res = (res + x * cnts[e][i + BASE]) % MOD;
			}
		}
		
		res = (res % MOD + MOD) % MOD;
		cout << res << '\n';
	}
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);

	LL f = 1;
	for(int i = 1; i <= DEG; ++i){
		f = f * -i % MOD;
	}
	for(int i = 0; i <= DEG; ++i){
		invs[i] = powmod(f, MOD - 2);
		f = f * (i + 1) % MOD;
		f = f * powmod(i - DEG, MOD - 2) % MOD;
	}

	int n, m;
	while(cin >> n >> m && n){
		solve(n, m);
	}
}
accuracy: 1
time_ms: 3600
memory_kb: 100020
final_rank: 14

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <queue>
using namespace std;

typedef long long LL;
typedef pair<int,int> pii;

const LL MOD = 1000000007;

const int DEG = 2100;
const int BASE = 4100;

void add(LL &x, LL y){
	x += y;
	if(x >= MOD){ x -= MOD; }
}

LL powmod(LL x, LL y){
	LL a = 1;
	while(y){
		if(y & 1){ a = a * x % MOD; }
		x = x * x % MOD;
		y >>= 1;
	}
	return a;
}

LL invs[DEG + 1];
LL sum1, sum2;

void solve(int n, int m){
	vector<vector<pii>> G(n);
	for(int i = 0; i < m; ++i){
		int s, t, d;
		cin >> s >> t >> d;
		G[s - 1].emplace_back(t - 1, d);
	}

	vector<vector<LL>> cnts(n, vector<LL>(BASE + DEG + 1));
	cnts[0][0] = 1;
	for(int u = 0; u < n; ++u){
		for(int i = 0; i < BASE + DEG; ++i){
			LL t = cnts[u][i];
			add(cnts[u][i + 1], t);
			for(const auto &p : G[u]){
				if(i + p.second <= BASE + DEG){
					add(cnts[p.first][i + p.second], t);
				}
			}
		}
	}

	vector<LL> ltmul(DEG + 2), rtmul(DEG + 2);
	int q;
	cin >> q;
	for(int qnum = 0; qnum < q; ++qnum){
		int e;
		LL t;
		cin >> e >> t;
		--e;

		LL res = 0;
		if(t <= BASE + DEG){
			res = cnts[e][t];
		}
		else{
			LL s = (t - BASE) % MOD;
			ltmul[0] = 1;
			for(int i = 0; i <= DEG; ++i){
				ltmul[i + 1] = ltmul[i] * (s - i) % MOD;
			}
			rtmul.back() = 1;
			for(int i = DEG; i >= 0; --i){
				rtmul[i] = rtmul[i + 1] * (s - i) % MOD;
			}
			for(int i = 0; i <= DEG; ++i){
				LL x = ltmul[i] * rtmul[i + 1] % MOD * invs[i] % MOD;
				res = (res + x * cnts[e][i + BASE]) % MOD;
			}
		}
		
		res = (res % MOD + MOD) % MOD;
		cout << res << '\n';
	}
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);

	LL f = 1;
	for(int i = 1; i <= DEG; ++i){
		f = f * -i % MOD;
	}
	for(int i = 0; i <= DEG; ++i){
		invs[i] = powmod(f, MOD - 2);
		f = f * (i + 1) % MOD;
		f = f * powmod(i - DEG, MOD - 2) % MOD;
	}

	int n, m;
	while(cin >> n >> m && n){
		solve(n, m);
	}
}
accuracy: 1
time_ms: 3530
memory_kb: 100092
final_rank: 12

code_snippet: #include<iostream>
#include<vector>
#include<string>
#include <algorithm>
#include <cstdint>
#include <time.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
typedef long long ll;
#define mod 1000000007
template <std::uint_fast64_t Modulus> class modint {
  using u64 = std::uint_fast64_t;
public:
  u64 a;
  constexpr modint(const u64 x = 0) noexcept : a(x % Modulus) {}
  constexpr u64 &value() noexcept { return a; }
  constexpr const u64 &value() const noexcept { return a; }
  constexpr modint operator+(const modint rhs) const noexcept {
    return modint(*this) += rhs;
  }
  constexpr modint operator-(const modint rhs) const noexcept {
    return modint(*this) -= rhs;
  }
  constexpr modint operator*(const modint rhs) const noexcept {
    return modint(*this) *= rhs;
  }
  constexpr modint operator/(const modint rhs) const noexcept {
    return modint(*this) /= rhs;
  }
  constexpr modint &operator+=(const modint rhs) noexcept {
    a += rhs.a;
    if (a >= Modulus) {
      a -= Modulus;
    }
    return *this;
  }
  constexpr modint &operator-=(const modint rhs) noexcept {
    if (a < rhs.a) {
      a += Modulus;
    }
    a -= rhs.a;
    return *this;
  }
  constexpr modint &operator*=(const modint rhs) noexcept {
    a = a * rhs.a % Modulus;
    return *this;
  }
  constexpr modint &operator/=(modint rhs) noexcept {
    u64 exp = Modulus - 2;
    while (exp) {
      if (exp % 2) {
        *this *= rhs;
      }
      rhs *= rhs;
      exp /= 2;
    }
    return *this;
  }
};

int main(){    
    //clock_t start = clock();
    using mint = modint<1000000007>;
    int n,m,q;
    while(scanf("%d %d",&n,&m)&& n!=0){
        //cerr << n << " " << m << endl;
        //cout << endl;
        vector<vector<pair<int,int> > > s(n);
        rep(i,m){
            int a,b,c;
            scanf("%d %d %d",&a,&b,&c);
            a--;b--;
            s[b].push_back(make_pair(a,c));
        }
        vector<vector<mint> > f(n);
        vector<int> g(n);
        rep(i,n){
            if(i==0){
                f[0].push_back(1);
                g[0] = 1;
                continue;
            }
            int mx_f = 0;
            int mx_g = 0;
            for(auto x : s[i]){
                if(f[x.first].size()!=0){
                    mx_g = max(mx_g,g[x.first]);
                }
            }
            for(auto x : s[i]){
                if(f[x.first].size()!=0){
                    mx_f = max( mx_f, x.second + (int)f[x.first].size() + mx_g - g[x.first] );
                }
            }
            f[i].resize(mx_f+1);
            g[i] = mx_g+1;
            for(auto x : s[i]){
                int id = x.first;
                int p = x.second;
                int k = mx_g - g[id];
                if(f[id].size()==0)continue;
                vector<mint> ff((int)f[id].size()+k);
                rep(j,(int)f[id].size()){
                    ff[j] = f[id][j];
                }
                rep(zz,k){
                    for(int j=(int)ff.size()-1;j>0;j--){
                        if(j!=0){
                            ff[j] = ff[j] - ff[j-1];
                        }
                    }
                }
                rep(j,(int)ff.size()){
                    f[i][j+p] += ff[j];                    
                }
                
            }
            while(1){
                if(f[i].size()==0)break;
                if(f[i][f[i].size()-1].value()==0){
                    f[i].pop_back();
                }else{
                    break;
                }
            }
            if(f[i].size()==0)g[i]=0;
        }
        scanf("%d",&q);
        // rep(i,q){
          
        //     int d,e;
        //     scanf("%d %d",&d,&e);
        //     d--;
        //     mint a = 1;
        //     if(f[d].size()==0||g[d]==0){
        //         printf("0\n");
        //         continue;
        //     }
        //     int p = g[d];
        //     rep(j,p-1){
        //         a *= (e-j+p-1);
        //     }
        //     mint b = 1;
        //     rep(j,p-1){
        //         b *= p-1-j;
        //     }
        //     a /= b;
        //     mint res = 0;
        //     rep(j,min(e+1,(int)f[d].size())){
        //         res += f[d][j] * a;
        //         a /=  e+p-1-j;
        //         a *=  (e-j);
        //         if(a.value()==0)break;
        //     }
        //     printf("%d\n",res.value());
        // }
        rep(i,q){
            int d,e;
            scanf("%d %d",&d,&e);
            d--;
            if(f[d].size()==0||g[d]==0){
                printf("0\n");
                continue;
            }
            int p = g[d];
            if(p==1){
              
              printf("1\n");
              continue;
            }
            p--;
            int len = f[d].size()+p+2;
            vector<mint> ss(len);
            bool breakflag =0;
            rep(k,len){
              ss[k] = max(0,e+p-k);
            }
            vector<mint> toleft(len);
            vector<mint> toright(len);
            rep(k,len){
              if(k%p==0){
                toright[k] = 1;
              }
              if(k%p!=0){
                toright[k] = ss[k-1];
                toright[k] *= toright[k-1];
                
              }
            }
            for(int k=len-1;k>=0;k--){
              toleft[k] = ss[k];
              
              if(k!=(len-1)&&k%p!=p-1){
                toleft[k] *= toleft[k+1];
                
              }
            }
            mint b = 1;
            rep(j,p){
                b *= p-j;
            }
            mint c = (mint)1/b;
            mint res = 0;
            mint a;
            rep(j,min(e+1,(int)f[d].size())){
                
                a = toleft[j] * toright[j+p];
                a *= c;
                

                if(a.value()==0)break;
                //cerr << f[d][j] << " " << a << endl;
                res += f[d][j] *a;
              
            }
            printf("%d\n",res.value());
        }
    }
    // clock_t end = clock();

    // const double time = static_cast<double>(end - start) / CLOCKS_PER_SEC * 1000.0;
    //cerr << time << endl;
    return 0;

}
accuracy: 1
time_ms: 7180
memory_kb: 29028
final_rank: 11

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <queue>
using namespace std;

typedef long long LL;
typedef pair<int,int> pii;

const LL MOD = 1000000007;

const int DEG = 2100;
const int BASE = 4100;

void add(LL &x, LL y){
	x += y;
	if(x >= MOD){ x -= MOD; }
}

LL powmod(LL x, LL y){
	LL a = 1;
	while(y){
		if(y & 1){ a = a * x % MOD; }
		x = x * x % MOD;
		y >>= 1;
	}
	return a;
}

LL invs[DEG + 1];

void solve(int n, int m){
	vector<vector<pii>> G(n);
	for(int i = 0; i < m; ++i){
		int s, t, d;
		cin >> s >> t >> d;
		G[s - 1].emplace_back(t - 1, d);
	}

	vector<vector<LL>> cnts(n, vector<LL>(BASE + DEG + 1));
	cnts[0][0] = 1;
	for(int i = 0; i < BASE + DEG; ++i){
		for(int u = 0; u < n; ++u){
			LL t = cnts[u][i];
			add(cnts[u][i + 1], t);
			for(const auto &p : G[u]){
				if(i + p.second <= BASE + DEG){
					add(cnts[p.first][i + p.second], t);
				}
			}
		}
	}

	vector<LL> ltmul(DEG + 2), rtmul(DEG + 2);
	int q;
	cin >> q;
	for(int qnum = 0; qnum < q; ++qnum){
		int e;
		LL t;
		cin >> e >> t;
		--e;

		LL res = 0;
		if(t <= BASE + DEG){
			res = cnts[e][t];
		}
		else{
			LL s = (t - BASE) % MOD;
			ltmul[0] = 1;
			for(int i = 0; i <= DEG; ++i){
				ltmul[i + 1] = ltmul[i] * (s - i) % MOD;
			}
			rtmul.back() = 1;
			for(int i = DEG; i >= 0; --i){
				rtmul[i] = rtmul[i + 1] * (s - i) % MOD;
			}
			for(int i = 0; i <= DEG; ++i){
				LL x = ltmul[i] * rtmul[i + 1] % MOD * invs[i] % MOD;
				res = (res + x * cnts[e][i + BASE]) % MOD;
			}
		}
		
		res = (res % MOD + MOD) % MOD;
		cout << res << '\n';
	}
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);

	LL f = 1;
	for(int i = 1; i <= DEG; ++i){
		f = f * -i % MOD;
	}
	for(int i = 0; i <= DEG; ++i){
		invs[i] = powmod(f, MOD - 2);
		f = f * (i + 1) % MOD;
		f = f * powmod(i - DEG, MOD - 2) % MOD;
	}

	int n, m;
	while(cin >> n >> m && n){
		solve(n, m);
	}
}
accuracy: 1
time_ms: 6900
memory_kb: 100036
final_rank: 17

code_snippet: #include <bits/stdc++.h>

#define int long long
#define inf  1000000007
#define pb push_back
  using namespace std;


int po(int r,int k){
	if(k==1) return r;
	if(k%2) return po(r,k-1)*r%inf;
	int v=po(r,k/2);
	return v*v%inf;
}

int inv(int r){
	return po(r,inf-2);
}


int dp[2005][6005];
vector<pair<int,int>> G[2005];


void solve(){
	int n,m;
	if(!(cin>>n>>m))exit(0);
	if(n==0) exit(0);
	for(int i=0;i<n;i++)G[i].clear();
	for(int i=0;i<n;i++)for(int j=0;j<=3*n+4;j++)dp[i][j]=0;
	dp[0][0]=1;
	vector<int> nyu(n,0);
	
	for(int i=0;i<m;i++){
		int y,yy,yyy;
		cin>>y>>yy>>yyy;
		y--,yy--;
		G[y].pb({yy,yyy});
		nyu[yy]++;
	}
	
	// topological sort
	vector<int> topo(n);
	for(int i=0;i<n;i++)topo[i]=i;
	assert((int)topo.size()==n);
	
	// DP t= 0 ~ 3*n
	for(auto v:topo){
		for(int i=1;i<=3*n;i++){
				dp[v][i]+=dp[v][i-1];
				dp[v][i]%=inf;
		}
		for(auto w:G[v]){
		
			for(int i=0;i+w.second<=3*n;i++){
				dp[w.first][i+w.second]+=dp[v][i];
				dp[w.first][i+w.second]%=inf;
			}
		}
	}
	
	// 
	vector<int> frac(n+1,1);
	for(int i=1;i<=n;i++)frac[i]=frac[i-1]*i%inf;
	vector<int> frac_inv(n+1,1);
	frac_inv[n]=inv(frac[n]);
	for(int i=n;i>0;i--)frac_inv[i-1]=frac_inv[i]*i%inf;
	
	int Q;
	cin>>Q;

	while(Q--){
		
		int e,t;
		cin>>e>>t;
		e--;
		if(t<=3*n){
			cout<<dp[e][t]<<endl;
		}
		else{
			// i = 2*n ~ 3*n を使ってn次式を復元
			vector<int>bunsi_mae(n+1,0);
			bunsi_mae[0]=1;
			for(int i=1;i<=n;i++){
				bunsi_mae[i]=bunsi_mae[i-1]*(t-2*n-i+1)%inf;
			}
			vector<int>bunsi_ato(n+1,0);
			bunsi_ato[n]=1;
			for(int i=n-1;i>=0;i--){
				bunsi_ato[i]=bunsi_ato[i+1]*(t-2*n-i-1)%inf;
			}
			int bunsi_all=1;
			for(int i=2*n;i<=3*n;i++){
				bunsi_all*=t-i;
				bunsi_all%=inf;
			}
			
			int ans=0;
			for(int i=2*n;i<=3*n;i++){
				int bunsi=bunsi_mae[i-2*n]*bunsi_ato[i-2*n]%inf;
				int bunbo=frac_inv[i-2*n]*((3*n-i)%2?(inf-1)*frac_inv[3*n-i]%inf:frac_inv[3*n-i])%inf;
				ans+=dp[e][i]*bunsi%inf*(bunbo)%inf;
				ans%=inf;
			}
			cout<<ans<<endl;
		}
	}
}

 signed main(){
 	while(1) solve();
 	return 0;

  }
accuracy: 1
time_ms: 2750
memory_kb: 97160
final_rank: 5