A state consists of N cities. Some of these cities are connected to each other by one - way roads. The time taken to travel from a particular city to any other city directly connected to it is 1 hour. The entire map of the state will be given. You will be given Q queries, each query asking you the number of ways to travel from city i to city j by exactly taking a time of P hours.
Two cities can be connected to each other by multiple roads. Each road in this case will be a distinct road. There is no such road which connects a city to itself ie. there are no self loops.
Input :
First line consists of N, the number of cities present in the state. The next line consists of R, the total number of roads directly connecting any 2 cities. The next R lines are such that each line contains two space seprated integers i and j, denoting that there exists a one - way road directly connecting city i to city j. The next line consists of Q, the number of queries. The next Q lines are such that each line contains 3 space - separated integers i , j , P . This query asks you the number of ways to travel from city i to city j by exactly taking a time of P hours. You must give the answer to each query modulo 10^9 + 7.
Output :
Print the answer to each query modulo 10^9 + 7 on a new line.
We are given a directed graph with N up to 50, R up to 100k, Q up to 100k in type1 with P <=10, and in type2 Q <=5 with P up to 1000. We need for each query (i, j, P) count number of walks of length exactly P from i to j. Since edges have weight 1 (each step is 1 hour), count walks of length P. This is classic: If we have adjacency matrix A (N x N) where A[i][j] = number of roads from i to j (since multiple distinct roads count). Then number of walks of length P from i to j is (A^P)[i][j]. So we need to compute these entries for many queries efficiently.
Constraints: N=50 small. So we can precompute matrix powers of A up to max P across queries. Since P can be up to 1000 in type2, and Q small, we can compute all powers up to max P via exponentiation by squaring? But for P up to 1000, precomputing all powers 1..maxP is fine as N=50, and matrix multiplication O(N^3) ~125k operations per multiplication, times 1000 = 125 million, maybe borderline but okay in C++ but Python might be heavy? However 50^3 =125000, times 1000 =125 million multiplications with modulo (1e9+7) which is doable in Python if optimized? 125 million modulo operations might be slow but maybe okay with PyPy and efficient loops? Could also use exponentiation per query, but Q up to 5 for large P, can do binary exponentiation per query O(N^3 log P) which is 125k * log2(1000) ~ 125k *10 =1.25M per query, very small. For Q up to 100k and P <=10, precomputing powers up to 10 is easy: compute A^1, A^2, ... A^10 via repeated multiplication: 10 * 125k =1.25M, fine. So we can handle both uniformly: compute matrix powers up to maxP if maxP is small (<=10) and also support large P via fast exponentiation on demand. But type2 has maxP up to 1000 but Q only <=5, so we can compute using binary exponentiation per query; each query we compute A^P and then answer (i,j). However binary exponentiation would compute the full matrix power each time? Actually we just need entry (i,j). But we could compute using repeated squaring of matrix to compute A^P, and then extract entry. Or we can precompute matrix powers of form A^(2^k) via binary exponentiation up to max power (like 2^k <= maxP), and then for each query compute the product of matrices that yields A^P but only compute the required entry without full matrix multiplication? Possibly we can do: For each query we want (e_i)^T * A^P * e_j. With precomputed powers we can compute vector-matrix multiplication. But since N=50, we can just compute the full matrix A^P by binary exponentiation using O(N^3 log P) per query, which is fine for Q<=5. So overall:
Read N.
Read R, then adjacency counts: A (N x N) filled with zero. For each road (u, v), increment A[u-1][v-1] by 1.
Read Q, then queries: store list of (i, j, P) (0-indexed).
Determine maxP among queries.
If maxP <= 10 (or maybe if Q large we can precompute), compute all powers up to maxP: power[0] = identity (length 0 walks: identity matrix). For p from 1 to maxP: power[p] = power[p-1] * A (matrix multiplication). Then answer each query by looking at power[P][i][j] mod MOD.
Else (maxP large, but Q small): For each query compute A^P via binary exponentiation and output entry. But we need to ensure we handle both efficiently. However type2 has P up to 1000, which is not huge; we can just precompute up to maxP=1000 anyway. 1000 * 125k = 125 million operations. Python might manage with careful implementation? Let's estimate: 125 million integer multiplications and additions mod 1e9+7. In Python, that's heavy. But we can perhaps optimize: Use list of lists, nested loops; Python loops are slow. 125 million operations could be ~5 seconds or more, maybe borderline. But constraints mention test files type1 and type2 separately, so we can adapt approach based on Q and maxP. Actually we can differentiate: If Q > 10? Actually type1 has Q up to 100k and P <=10, so precomputing up to 10 is fine. Type2 has Q <=5 and P up to 1000. For type2, we can compute per query using binary exponentiation: each query does up to log2(1000) ≈10 matrix multiplications, each O(N^3)=125k, total per query 1.25M, for 5 queries ~6.25M, which is definitely fine. So we can implement a generic solution: compute maximum P. If maxP <= 10 or Q is large? Actually we need to handle both efficiently: When maxP is large but Q is small, we use binary exponentiation per query. When maxP is small, we precompute. But there might be cases where maxP >10 but Q is large? According to constraints, either (type1) P<=10 and Q up to 1e5, so maxP <=10 always. Or (type2) Q<=5 and P up to 1000, so Q small. So we can condition on Q: if Q > 10? Actually Q can be up to 1e5, that's obviously large, so then P <=10 as per constraints. So we can simply check: if maxP <= 10 or Q > 10? But safe: If maxP > 10, then we assume Q is small (<=5) and use binary exponentiation per query. Otherwise, precompute.
But there is a nuance: The problem description says there are two types of test files, but they are not explicitly indicated in input; we have to read input and handle accordingly. So we need to auto-detect which approach to take. Since N is small, we can always use binary exponentiation for each query regardless of Q, but Q up to 100k would be too heavy: each query log2(P) matrix multiplications, worst-case P <=10, log2(10)~4, each multiplication 125k operations => 500k operations per query, times 100k = 50 billion, impossible. So we cannot do per query binary exponentiation for many queries.
Thus we must precompute for many queries. However maxP is at most 10 when Q is large, so precomputing up to 10 is cheap. So our detection can be: After reading queries, if maxP <= 10, precompute all powers up to maxP; else compute per query using binary exponentiation.
Edge: Could there be a test with maxP=0? P >=1 per constraints (1 ≤ P). So fine.
Now we need matrix multiplication modulo MOD=10**9+7.
Implementation details:
Represent matrices as list of lists of ints. Use N up to 50.
Function mat_mul(A, B):
N = len(A)
result = [[0]*N for _ in range(N)]
# We can do standard triple loop with i,k,j order to improve cache? Because N small, any order works but maybe we can use i,k,j for better use of Python's list accessing? Actually Python loops are slow; we can attempt to minimize inner loops by using sum of products? But we can also use numpy? Not allowed likely.
# Since N=50, triple loop with 125k iterations per multiplication; each iteration has a multiplication and addition mod. This is okay.
# However we will do: for i in range(N): for k in range(N): if A[i][k]!=0: aik = A[i][k]; for j in range(N): result[i][j] = (result[i][j] + aik * B[k][j]) % MOD
# This exploits sparsity? A may be dense? But with N=50, it's okay; but A may be sparse? However after powers, it may become dense. Anyway.
return result
But in precomputation we need to compute A^1, A^2,... A^maxP. We can compute iteratively: cur = A; for p in 1..maxP: store cur; then cur = cur * A. So each multiplication is dense. That's fine.
For binary exponentiation: we precompute powers of A for exponents that are powers of two: A_pow[0]=A, A_pow[1]=A^2, A_pow[2]=A^4, ... up to highest bit. Then for each query with P, we compute result matrix = identity, and multiply those powers where bit set, using matrix multiplication. But we need the full matrix to answer (i,j)? Actually we only need one entry, but if we compute the full matrix it's O(N^3 log P). Since N is small and Q is small, that's fine. So we can compute full product matrix.
Alternatively we could compute vector from i: start with vector v (size N) with 1 at i and zeros elsewhere, multiply by relevant matrices from left: v = v * (A^P). This reduces to O(N^2 log P) per query, which is even faster. Since Q small (<=5) but N small anyway, but for large Q not needed. But we can implement for binary exponentiation per query: use vector multiplication with precomputed A_pow2. That would be O(N^2 log P) per query, which for Q up to 5 is trivial. That might be more efficient. However simpler to just compute full matrix using binary exponentiation. But to be clean, we can implement function get_power(P) that returns matrix A^P using binary exponentiation with precomputed powers of two (if we want to reuse across queries). Since Q small, we can just compute per query separately; but we can precompute A_pow2 up to maxP and then for each query multiply corresponding matrices. However note that binary exponentiation per query with repeated squaring but recomputing powers each time? We can compute A_pow2 once up to highest exponent needed among all queries. Then for each query, we can compute result = identity; for each bit, if bit set, result = result * A_pow2[bit]. That's O(N^3 log P) per query. But we can also compute for each query using vector multiplication O(N^2 log P) by applying matrices to a starting vector. Since N=50, the difference is minimal. We'll just compute full matrix.
But note: For type1 with many queries, we use precomputed list powers[P] (full matrix). So we answer instantly.
Now we must parse input. The input format: first line N, then line R, then R lines each with i j, then line Q, then Q lines each with i j P. Possibly blank lines? Not indicated. We'll use sys.stdin.read().split() to get tokens.
Edge cases: Multiple roads between same pair: they count as distinct walks? In adjacency matrix, we set count = number of roads. Then number of walks of length 1 is that count. For longer walks, the count multiplies accordingly (since each road is distinct). That's correct.
We must output answer modulo MOD.
Let's write code.
Implementation steps:
MOD = 10**9+7.
Read all ints via sys.stdin.buffer.read().split()
iter over tokens.
N = int(next_token)
R = int(next_token)
Initialize A = [[0]*N for _ in range(N)]
For _ in range(R): u = int(next_token)-1; v = int(next_token)-1; A[u][v] += 1
Q = int(next_token)
queries = [] ; maxP = 0
For _ in range(Q): i = int(next_token)-1; j = int(next_token)-1; p = int(next_token); queries.append((i,j,p)); maxP = max(maxP, p)
If maxP <= 10 or Q > 10? Actually to decide: If maxP <= 10 (since type1), we can precompute. But what if maxP > 10 but Q is also >10? That shouldn't happen per constraints, but for safety, we could decide: if Q > 100 (something) we know P <=10? But maybe testcases outside constraints? Let's just base on maxP: if maxP <= 10, precompute; else use binary exponentiation per query. Because if maxP >10 then Q must be small (<=5) as per constraints, but even if not, per-query binary exponentiation would be too heavy for many queries, but we assume testdata respects constraints. So we can do:
if maxP <= 10:
precompute powers up to maxP.
for each (i,j,p): output powers[p][i][j] % MOD.
else:
precompute A_pow2 for powers of two up to maxP via repeated squaring (i.e., compute A^1? Actually we need A^(2^k) for k=0..floor(log2(maxP))). We can compute starting from A, and square repeatedly.
For each query:
res = identity matrix
exp = p
bit = 0
while exp > 0:
if exp & 1:
res = mat_mul(res, A_pow2[bit])
exp >>= 1
bit += 1
answer = res[i][j]
print(answer)
But careful: We need to ensure A_pow2[0] = A (2^0), A_pow2[1] = A^2, etc. So we compute that list.
Actually we can also compute using fast exponentiation function that multiplies matrices.
But we must ensure we compute A_pow2 only once, not per query. Since maxP may be up to 1000, we need up to log2(1000) ≈ 10 matrices; we can compute them.
But also note that for binary exponent we need to use the same matrix multiplication routine.
Now matrix multiplication: For N=50, we can implement with loops and maybe using local variables for speed. Write:
def mat_mul(A, B):
n = len(A)
# Precompute B column-wise? Actually we can keep row-major; standard triple loop i, k, j with k middle is okay.
# But to speed up, we can do i, k, j and if A[i][k] != 0: then do inner loop.
C = [[0]*n for _ in range(n)]
for i in range(n):
Ai = A[i]
Ci = C[i]
for k in range(n):
aik = Ai[k]
if aik:
Bk = B[k]
# inner loop over j
# Since mod, we can compute contributions.
# For j in range(n): Ci[j] = (Ci[j] + aik * Bk[j]) % MOD
# To reduce modulo operations, we can accumulate and then mod? but risk overflow: aik up to MOD-1, Bk[j] up to MOD-1, product up to ~1e18, Python ints arbitrary precision, but we can mod each addition. But we can also accumulate without mod and mod after inner loop? But sum of up to N=50 products each up to 1e18 gives up to 5e19, still within Python int, but eventually we may have many additions across k, up to N=50, total sum up to 2.5e20 which is fine. However after each addition we can mod to keep numbers smaller, but modulo operation cost. We can try to accumulate in a temporary variable and mod at the end of j loop? Actually we need per cell final mod. Since we do many contributions, we can accumulate in Ci[j] as int and after all k, we mod each Ci[j]. But Ci[j] could become huge: for A^p, numbers can become huge (mod MOD), but we mod at each multiplication step to keep values bounded; but if we defer mod until end of multiplication, intermediate values could be huge: For worst-case, each product could be up to (MOD-1)^2 ~1e18, sum up to N=50 such => 5e19, still fine for Python. But after many multiplications in exponentiation, if we defer mod, numbers could blow up exponentially? But we always mod after each matrix multiplication. So within mat_mul, we should mod the final result to keep numbers in [0,MOD). So we can either mod after each addition or after inner loop for each cell. Since Python big ints are okay, but performance wise, modding each addition may be overhead; we could accumulate sum in a temporary variable for each (i,j) by iterating k and then mod at end. But that changes loop order: we could loop i, j, then for k sum A[i][k]*B[k][j] then mod. That is i,j outer double loop, then inner k, which is also 125k iterations. Which is faster? Typically i,k,j with check for non-zero may be faster if matrix is sparse? But after a few powers it becomes dense. The i,j,k order might be simpler and allows using built-in sum? Let's just do triple loops with mod after each addition; it's simpler and okay for 125k * something. For each multiplication we have ~125k inner iterations (i,k,j). That's fine.
But I'll implement as:
def mat_mul(A, B):
n = len(A)
C = [[0]*n for _ in range(n)]
for i in range(n):
for k in range(n):
aik = A[i][k]
if aik:
rowC = C[i]
rowB = B[k]
# unroll? we can do for j in range(n): rowC[j] = (rowC[j] + aik * rowB[j]) % MOD
# but modulo is expensive; we can compute addition and then if >= MOD subtract? But since we need mod each time to keep numbers bounded, we can compute temp = aik * rowB[j]; then add to rowC[j]; after inner loop, we can apply mod for each rowC[j]? But rowC[j] gets contributions from multiple k; we could accumulate then mod at end of k loop? Actually after each k, rowC[j] might exceed Python int but we can mod after each j? Alternative: compute rowC[j] += aik * rowB[j]; and after finishing all k for a given i, we mod rowC[j]. That reduces mod operations to N per i (since after k loop, we mod each element). That could be faster. So we can do:
for i in range(n):
temp = [0]*n
for k in range(n):
aik = A[i][k]
if aik:
bk = B[k]
for j in range(n):
temp[j] += aik * bk[j]
for j in range(n):
C[i][j] = temp[j] % MOD
return C
This accumulates in a temporary list of ints (maybe Python ints) without mod, then mod at end. The numbers may become large: For each i, we have N * N multiplications => up to 2500? Actually N=50, for each i we sum over k (50) each inner loop adds product to temp[j] (50 values). So max temp[j] accumulation: sum over k of aik * bk[j]. aik and bk[j] each up to MOD-1 (1e9). So each product up to 1e18, sum of 50 such => 5e19, fine. So we can do this.
But careful: We must ensure we don't overflow Python's memory, but Python ints are arbitrary precision, so okay.
Thus mat_mul can be implemented with i, k, j loops and temp accumulator.
Alternatively, we can use list comprehension with sum, but that would be slower.
Let's implement:
def mat_mul(A, B):
n = len(A)
C = [[0]*n for _ in range(n)]
for i in range(n):
row = [0]*n
Ai = A[i]
for k in range(n):
aik = Ai[k]
if aik:
Bk = B[k]
# manually unroll j loop
for j in range(n):
row[j] += aik * Bk[j]
# mod row
mod = MOD
for j in range(n):
row[j] %= mod
C[i] = row
return C
Now identity matrix function:
def identity(n):
I = [[0]*n for _ in range(n)]
for i in range(n):
I[i][i] = 1
return I
Now, for precomputation up to maxP small:
powers = [None]*(maxP+1)
cur = A
for p in range(1, maxP+1):
powers[p] = cur
cur = mat_mul(cur, A) # careful: This computes A^p then next step multiply by A to get A^(p+1). Actually if cur = A at p=1, then after storing, cur = cur * A => becomes A^2. So works.
But note: For p=0 we could store identity, but not needed as P>=1.
But we need to answer queries for P exactly; we have powers[P]. However we must be careful: When maxP = some value, we compute up to that. Since we start cur = A (A^1). For p=1, store cur (A^1). Then cur = cur * A = A^2. Then for p=2, store cur (A^2). That's correct.
Alternatively we could compute with DP: power[0]=I; for i in 1..maxP: power[i] = mat_mul(power[i-1], A). That is simpler. I'll use that to avoid confusion:
power = [None]*(maxP+1)
power[0] = identity(N)
for p in range(1, maxP+1):
power[p] = mat_mul(power[p-1], A)
Then answer = power[P][i][j] % MOD.
For the small maxP case, we must ensure we compute identity for p=0 not needed but may be used if P=0, but constraints say P>=1 so fine.
Now for binary exponentiation case:
We precompute A_pow2: list where A_pow2[k] = A^(2^k).
Compute as:
A_pow2 = []
current = A
while maxP > 0:
A_pow2.append(current)
current = mat_mul(current, current)
maxP >>= 1 # Actually we need up to highest bit of maxP among queries. Better compute up to floor(log2(maxP_max)). Let's precompute by repeatedly squaring until 2^k > maxP_max.
We'll compute:
maxP_all = max(p for ,,p in queries)
exp = maxP_all
A_pow2 = [A]
while (1 << len(A_pow2)) <= exp:
next_pow = mat_mul(A_pow2[-1], A_pow2[-1])
A_pow2.append(next_pow)
Then for each query with P:
res = identity(N)
bit = 0
while P > 0:
if P & 1:
res = mat_mul(res, A_pow2[bit])
P >>= 1
bit += 1
ans = res[i][j] % MOD
print(ans)
But careful: we use P variable; better copy p.
Now potential issues: For Q large, we precompute powers up to maxP. But maxP could be up to 10, which is small. That is fine.
We compute adjacency matrix; then compute powers accordingly.
Let's manually check? Not needed.
Implementation in Python.
Potential performance concerns:
For R up to 100k, reading and building adjacency matrix is O(R) fine.
For precomputation up to maxP=10, 10 matrix multiplications each O(50^3)=125k loops, total 1.25M loops of innermost addition; each loop does a few operations. Should be fast.
For many queries (100k), answering by direct index lookup O(1) each, fine.
Now we need to output each answer on new line.
One more nuance: In the precomputation approach, we need to compute matrix powers correctly. We must ensure that for P=0 we have identity, but not used.
Now, what about modulo? The answer is modulo MOD, but our matrix multiplication already does mod at each multiplication (or at end of each row). That's fine.
Now let's code.
But we also need to decide which approach to use. We'll compute maxP and Q. If maxP <= 10, we use precomputation; else we use binary exponentiation. However consider a scenario where maxP=10 but Q also large, that's fine. If maxP=20 but Q=5 (maybe they didn't restrict exactly but could happen?), then our precomputation up to 20 would be 20 * 125k = 2.5M, still okay. Actually 20 * 125k = 2.5M, that's also fine. Could we just always precompute up to maxP regardless of value? For maxP up to 1000, 1000 * 125k = 125M loops; might be borderline but possibly within time if optimized? Usually Python can handle around 50-100 million simple operations per second? Actually CPython might handle about 50 million simple integer ops per second? But not guaranteed. And the environment may have time limits. Since we have two types of test files, likely they expect efficient handling for both. For type2 with P up to 1000 and Q <=5, binary exponentiation is definitely safer and also simpler to implement (since we only need to compute up to 10 squarings and per query a few multiplications). So better to use binary exponent for larger P.
But what if maxP is 100 and Q is 10? Not specified, but maybe constraints guarantee the dichotomy. We'll stick with decision: if maxP > 10: use binary exponentiation per query. Because Q must be small in that case. This covers type2 and avoids heavy precomputation.
But we should check: In type1, P <=10, so maxP <=10 -> precomputation. In type2, P can be up to 1000 -> maxP >10 -> binary exponentiation. Good.
One more nuance: In type2, Q <=5, but we could also precompute powers up to maxP using DP (1000 multiplications) and answer quickly. If we implement both ways, it might still be okay as 125M ops might pass with PyPy? Possibly, but let's not rely on that. We'll use binary exponentiation for >10.
Now we must ensure we handle the case where P is 0? Not in constraints, ignore.
Now code.
But before writing, consider that in binary exponentiation we need to compute A_pow2 up to highest bit of maxP. That uses matrix squaring. Each squaring is a matrix multiplication. The number of squarings needed is floor(log2(maxP)) + 1. For maxP=1000, that's 10 squarings. Each squaring O(N^3)=125k loops; 10 => 1.25M loops, fine. Then each query may involve up to log2(P) matrix multiplications (when building result). For 5 queries, that's about 5*10=50 matrix multiplications => ~6.25M loops. Total maybe ~7.5M loops, still fine.
But note: For each query we multiply matrices as we combine the binary powers. However if we have many queries, we could compute A^P for each distinct P and reuse? But Q small so not needed.
Now implement mat_mul as described.
Potential micro-optimizations: Use local variables for MOD, n, and maybe use list comprehension for row creation. But fine.
Query1: 1->2 P=1 -> A[0][1]=1 -> output 1. ok.
Query2: 2->1 P=2 -> A^2[1][0]? Let's see: paths of length2 from city2 to city1? There are no paths perhaps, 0. ok.
Query3: 1->4 P=3. Let's compute quickly: paths of length3 from 1 to 4? 1->2->5->4? but 2->5,5->4 -> yes (1->2,2->5,5->4) length3. Also 1->2->3->4? (1->2,2->3,3->4) -> yes. Also 1->5->4->? That would be length2? 1->5->4 is length2, not 3. 1->2->5->4 is length3, 1->2->3->4 is length3. So 2. output 2. ok.
Query4: 1->6 P=3. Paths: 1->2->3->4->6? that's length4. 1->2->5->4->6? length4. Actually we need length3: 1->?->?->6. 6 is only reachable from 4. So need path length3 ending at 4 then step to 6 would be length4. So only path if there is direct to 6? No. Possibly 1->5->4->6 is length3? Wait: edges: 1->5 (1 step), 5->4 (1 step), 4->6 (1 step): total 3 steps. Yes! That's a path: 1->5->4->6. Also 1->2->5->4->6 is length4. 1->2->3->4->6 length4. So only one path of length3? Also 1->2->? Actually 1->2->?->6: need two intermediate. 2 can go to 5 or 3. From 5 go to 4 then 6: 2->5->4->6 is length3 from 2 to 6; but from 1 it would be length4 if start at 1. So only 1->5->4->6 is length3. Also could there be 1->2->? maybe 2->?->6 directly? no. So answer 1. output matches.
Query5: 1->6 P=4. Paths: 1->2->5->4->6 length4; 1->2->3->4->6 length4; also 1->5->4->? maybe 4->? no other. Also 1->2->? Actually 1->2->5->4->6 and 1->2->3->4->6; also 1->5->4->? maybe 4->6 only. So that's 2 paths. Also 1->2->? could there be 1->2->? multiple roads? Not. So 2. output 2. matches.
Query6: 6->1 P=8 -> probably 0. matches.
So sample works.
Now we need to implement and test.
Potential pitfalls: Input reading: after reading R lines, there might be newline before Q. We'll use tokenization.
Edge Cases: Multiple roads between same pair: ensure we increment count, not set to 1.
Now code.
Will we need to use sys.setrecursionlimit? Not.
Now we produce final code.
Let's write:
import sys
MOD = 10**9+7
def mat_mul(A, B):
n = len(A)
C = [[0]*n for _ in range(n)]
for i in range(n):
row = [0]*n
Ai = A[i]
for k in range(n):
aik = Ai[k]
if aik:
Bk = B[k]
# inner loop
for j in range(n):
row[j] += aik * Bk[j]
# mod
for j in range(n):
row[j] %= MOD
C[i] = row
return C
def identity(n):
I = [[0]*n for _ in range(n)]
for i in range(n):
I[i][i] = 1
return I
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
it = iter(data)
N = next(it)
R = next(it)
A = [[0]*N for _ in range(N)]
for _ in range(R):
u = next(it)-1
v = next(it)-1
A[u][v] += 1
Q = next(it)
queries = []
maxP = 0
for _ in range(Q):
i = next(it)-1
j = next(it)-1
p = next(it)
queries.append((i, j, p))
if p > maxP:
maxP = p
code
if maxP <= 10: # precompute all powers up to maxP
# compute power[0] = I, power[1] = A, etc.
power = [None]*(maxP+1)
power[0] = identity(N)
for p in range(1, maxP+1):
power[p] = mat_mul(power[p-1], A)
out_lines = []
for i, j, p in queries:
ans = power[p][i][j] % MOD
out_lines.append(str(ans))
sys.stdout.write("\n".join(out_lines))
else:
# binary exponentiation per query
# precompute A_pow2 up to highest bit of maxP
# Actually we need maxP for all queries to determine highest bit
maxP_all = max(p for _,_,p in queries)
A_pow2 = [A] # A^(2^0)
# while (1 << len(A_pow2)) <= maxP_all: compute next square
while (1 << len(A_pow2)) <= maxP_all:
next_mat = mat_mul(A_pow2[-1], A_pow2[-1])
A_pow2.append(next_mat)
out_lines = []
for i, j, p in queries:
res = identity(N)
bit = 0
pp = p
while pp > 0:
if pp & 1:
res = mat_mul(res, A_pow2[bit])
pp >>= 1
bit += 1
ans = res[i][j] % MOD
out_lines.append(str(ans))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
Now test with sample.
Let's simulate quickly using Python? We'll trust.
Potential bug: In the else branch, we precompute A_pow2 using while (1 << len(A_pow2)) <= maxP_all. Suppose maxP_all = 8 (1000). 2^0=1, len=1, 1<=1000 true -> compute square: A^2, add. Now len=2, 2^2=4<=1000 true -> compute A^4, add. len=3, 2^3=8<=1000 true -> compute A^8, add. len=4, 2^4=16<=1000 true -> compute A^16, add. ... eventually after k=9, 2^9=512<=1000 true -> compute A^512, add; k=10, 2^10=1024<=1000 false, stop. So we have up to A^(2^9) if needed? Actually for maxP=1000, highest bit is 2^9=512, but we also need 2^10=1024? Not because if p=1000, its binary representation uses bits: 1000 = 512+256+128+64+32+8? Actually 512+256=768; +128=896; +64=960; +32=992; +8=1000. So we need bits up to 512 (2^9). We have A_pow2[0]=A^1, [1]=A^2, [2]=A^4, [3]=A^8, [4]=A^16, [5]=A^32, [6]=A^64, [7]=A^128, [8]=A^256, [9]=A^512. Our while condition ensures that when len=10, 2^10=1024 > maxP_all, so we stop after having computed up to len=9 (since after appending for len=9, len becomes 10, then while checks with len=10? Actually careful: In loop we compute next_mat based on current last element, then append. We start with A_pow2 = [A] (len=1). Then while condition: (1 << len(A_pow2)) <= maxP_all. At start, len=1, 2^1=2 <= maxP? If maxP>=2, true, then compute square of A_pow2[-1] (which is A) -> A^2, append. Now len becomes 2. Now condition checked: 2^2=4 <= maxP? if true, compute next, etc. So the loop continues as long as 2^(current length) <= maxP_all. After we compute and append for length L (where L is the new length after appending), the condition uses the new length for next iteration. This yields that after finishing, we have A_pow2 such that for all k from 0 to len-1, we have A^(2^k) computed. But we might have computed one extra beyond needed? Let's test: Suppose maxP=1. Initially A_pow2=[A], len=1. while condition: 2^1=2 <=1? false, so loop not entered. So we have only A^1. That's fine because we need only bit0 if p=1.
Suppose maxP=2. Initially [A], len=1; condition 2<=2 true, so compute A^2 and append. Now len=2. Now condition 4<=2 false. So we have A^1 and A^2. For p=2, we need A^2 (bit1). Good.
Suppose maxP=3. We need bits 1 and 2 (2 and 1). Actually 3 = 2+1. Need A^1 and A^2. Our loop: start [A], len=1, 2<=3 true -> compute A^2, append -> len=2. Now condition 4<=3 false. So we have A^1 and A^2, sufficient.
Suppose maxP=4. Need A^4. But we also need A^2? For p=4, binary 100, need A^4. Do we have A^4? Our loop: start [A] len=1, 2<=4 true -> compute A^2, append -> len=2; condition 4<=4 true -> compute A^4 (square of A^2), append -> len=3; condition 8<=4 false. So we have A^1, A^2, A^4. Good.
Thus condition (1 << len) <= maxP works. We use len(A_pow2) in condition before we compute the next power? Actually we need to compute up to highest bit floor(log2(maxP)). The condition (1 << current_len) <= maxP ensures we compute next power as long as 2^current_len <= maxP. At current_len = number of matrices already computed. Initially we have 1 matrix (2^0). So if 2^1 <= maxP, we need A^2. That's correct.
Now for each query we compute res = identity and multiply by A_pow2[bit] when bit set. Good.
But note: For p=0 (not possible) would be identity.
Now, we need to ensure that we do not modify original A when squaring; our mat_mul returns new matrix.
Now about memory: For precomputation of powers up to maxP=10, we store 11 matrices of size 50x50 -> small.
Now, test with sample using maxP=8? Actually sample has maxP=8. Since maxP=8 <=10, we go into precompute branch. So we compute powers[0..8]. That's fine.
Now ensure that the adjacency matrix for sample yields correct outputs.
Now, final code.
Potential improvements: Use 'MOD = 1000000007' constant.
Now, edge cases: R may have duplicate edges; we increment count.
Now, I'll produce final answer.
But also note: In binary exponent per query, we are recomputing res each time, which is a full matrix multiplication each time a bit is set. Could we optimize by using vector multiplication? But not needed.
One more nuance: In the else branch, we compute A_pow2 using the original A. But what if we have many queries with different P? That's fine.
Now, verify for a scenario where maxP >10 but Q is very large (maybe unexpected). The binary exponent per query would be too slow. But we trust constraints.
One more subtle: In type2, P can be up to 1000, but Q <=5, but also R can be up to 100k. That's fine.
Now finalize.
Before final, consider using sys.stdout.write with newlines.
Now, I'll provide final code with comments.
Potential micro-optimization: In mat_mul, use 'for j in range(n): row[j] = (row[j] + aik * Bk[j])' without modulo inside loop, then after k loop we mod. But we need to ensure row[j] doesn't get too big. As argued, it's okay.
But one more thought: The multiplication may be performed many times in binary exponentiation. The numbers could become quite large if we defer modulo? For example, squaring a matrix where entries are up to MOD-1 may produce sums of up to N * (MOD-1)^2. For N=50, that's about 50 * 1e18 = 5e19, still within Python's integer range. After repeated squaring without modulo, the numbers would grow exponentially (like after many squarings, entries could become astronomically huge, causing performance issues). However in binary exponent per query, we always mod after each multiplication because our mat_mul does mod at the end of each row. So entries stay within MOD. In the accumulation row[j] we sum products without mod, but after each row we mod, so numbers are reduced. So no blow-up.
But careful: In mat_mul, we compute row[j] += aik * Bk[j] for all k, then mod row[j]. The intermediate row[j] during accumulation can become up to about N * (MOD-1)^2. That's okay. However if we do many matrix multiplications (like squaring) repeatedly, we always mod after each multiplication. So numbers stay bounded.
Now, if we were to not mod during the accumulation, it's fine.
Now, regarding performance: Using Python's int multiplication and addition, it's fine.
Now, we can also implement using numpy? Not allowed on standard judges? Probably not.
Now, final answer.
But wait: The problem statement: "Two cities can be connected to each other by multiple roads. Each road in this case will be a distinct road." So adjacency counts indeed.
Now, answer.
Now, but there is a twist: Could there be self loops? They say there are no self loops. So fine.
Now, we produce final solution.
But perhaps we can even more simplify: Since N <= 50, we can precompute all powers up to 1000 always, but we want to be safe. However let's stick with our decision.
Now, I'll write final code with comments.
One more check: In else branch, we compute A_pow2 list. However note that we compute squaring of matrices that might become dense. That's okay.
Now, we can also precompute once the binary powers and then answer each query using those. That's what we do.
Now, finalize.
One potential bug: In else branch, we compute A_pow2 starting from A. But for queries with P=0? Not possible.
Now, test with a small custom case:
N=2, R=2 edges: 1->2, 1->2 (two distinct roads). So A[0][1]=2. Query: 1->2 P=1 =>2. Good. Our code: adjacency built accordingly. Precompute or binary exponent accordingly. Should work.
Now, final answer.
But note: In our else branch, we compute A_pow2 up to highest power needed. However we also need to use identity for multiplication. That's fine.
Now, consider that the number of bits for maxP up to 1000 is 10. So A_pow2 length up to 10. Good.
Now, output format: each answer on new line.
Now, final code.
But also there is possibility that maxP=0? No.
Now, I'll provide solution.
Before final, think about reading input: using sys.stdin.buffer.read().split() returns list of bytes; mapping to ints works.
Now, handle case where there are no queries? Q=0? Not per constraints, but still handle: if Q==0, output nothing. Our code will read Q=0, queries empty, maxP=0, then go to branch maxP<=10, precompute power[0] only, but then no output. Works.
Now, done.
Potential memory: For precomputation powers up to maxP, we store matrices as list of lists of ints. That's fine.
Now, final answer.
Wait, I realize: In the else branch (maxP>10), we also have to consider that Q might be up to 100k? Not per constraints, but if a test mistakenly has large Q and P>10, our solution would be too slow. But we trust constraints.
But we can also add fallback: if Q * log2(maxP) is large, maybe use precomputation up to maxP if maxP not too big, like if maxP <= 1000 and Q * log2(maxP) > some threshold? But not necessary.
Now, I think final solution is fine.
I'll now produce final answer. ```python
import sys
MOD = 10**9 + 7
def mat_mul(A, B):
"""Multiply two N x N matrices modulo MOD."""
n = len(A)
C = [[0] * n for _ in range(n)]
for i in range(n):
# accumulator for row i
row = [0] * n
Ai = A[i]
for k in range(n):
aik = Ai[k]
if aik:
Bk = B[k]
# inner loop over columns
for j in range(n):
row[j] += aik * Bk[j]
# apply modulo
for j in range(n):
row[j] %= MOD
C[i] = row
return C
def identity(n):
I = [[0] * n for _ in range(n)]
for i in range(n):
I[i][i] = 1
return I
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
it = iter(data)
code
N = next(it)
R = next(it)
# adjacency matrix: A[u][v] = number of direct roads u -> v
A = [[0] * N for _ in range(N)]
for _ in range(R):
u = next(it) - 1
v = next(it) - 1
A[u][v] += 1
Q = next(it)
queries = []
maxP = 0
for _ in range(Q):
i = next(it) - 1
j = next(it) - 1
p = next(it)
queries.append((i, j, p))
if p > maxP:
maxP = p
# ----- decide strategy based on constraints -----
if maxP <= 10: # Type 1: many queries, small P
# pre‑compute A^0, A^1, ..., A^maxP
power = [None] * (maxP + 1)
power[0] = identity(N)
for k in range(1, maxP + 1):
power[k] = mat_mul(power[k-1], A)
out = []
for i, j, p in queries:
out.append(str(power[p][i][j] % MOD))
sys.stdout.write("\n".join(out))
else: # Type 2: few queries, possibly large P
# pre‑compute A^(2^k) for all needed bits
maxP_all = max(p for _, _, p in queries)
pow2 = [A] # pow2[0] = A^(2^0)
while (1 << len(pow2)) <= maxP_all:
pow2.append(mat_mul(pow2[-1], pow2[-1]))
out = []
for i, j, p in queries:
# binary exponentiation: multiply matrices for set bits
res = identity(N)
bit = 0
while p:
if p & 1:
res = mat_mul(res, pow2[bit])
p >>= 1
bit += 1
out.append(str(res[i][j] % MOD))
sys.stdout.write("\n".join(out))