Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # from sys import stdin as infile
- import io
- infile = io.StringIO("""\
- 4 2
- 1 0 0 1
- 1 2 3 4
- 5 6 7 8
- 1 3 3 1
- 5 5 1 2
- 5 5 3 3
- """)
- N, M = map(int, infile.readline().split())
- data = [tuple(map(int, infile.readline().split()))
- for i in range(N)]
- queries = [tuple(map(int, infile.readline().split()))
- for i in range(M)]
- MOD = 10**9 + 7
- def product(M1, M2):
- a11, a12, a21, a22 = M1
- b11, b12, b21, b22 = M2
- return (
- (a11*b11 + a12*b21) % MOD,
- (a11*b12 + a12*b22) % MOD,
- (a21*b11 + a22*b21) % MOD,
- (a21*b12 + a22*b22) % MOD,
- )
- tree = [None]*len(data) + data
- rev_tree = [None]*len(data) + data
- for i in range(len(data)-1, 0, -1):
- tree[i] = product(tree[i<<1],
- tree[(i<<1) | 1])
- rev_tree[i] = product(rev_tree[(i<<1) | 1],
- rev_tree[i<<1],)
- ID = (1, 0, 0, 1)
- def forward_query(a, b):
- assert a <= b
- left = right = ID
- a += len(data)
- b += len(data) + 1
- while a < b:
- if a & 1:
- left = product(left, tree[a])
- a += 1
- if b & 1:
- b -= 1
- right = product(tree[b], right)
- a >>= 1
- b >>= 1
- return product(left, right)
- def reverse_query(a, b):
- assert a >= b
- a, b = b, a
- left = right = ID
- while a < b:
- if a & 1:
- left = product(tree[a], left)
- a += 1
- if b & 1:
- b -= 1
- right = product(right, tree[b])
- a >>= 1
- b >>= 1
- return product(right, left)
- def query(a, b):
- a -= 1
- b -= 1
- if a <= b:
- return forward_query(a, b)
- else:
- return reverse_query(a, b)
- output = []
- for K, V, a, b in queries:
- a11, a12, a21, a22 = query(a, b)
- KK = (a11*K + a12*V) % MOD
- VV = (a21*K + a22*V) % MOD
- output.append(f"{KK} {VV}")
- M1, M2, M3, M4 = data
- p = product
- q = query
- assert p(M1, M2) == q(1, 2)
- assert p(M3, M4) == q(3, 4)
- assert p(M2, M3) == q(2, 3)
- assert p(M2, M1) == q(2, 1)
- assert p(p(M1, M2), M3) == q(1, 3)
- assert p(p(M3, M2), M1) == q(3, 1)
- assert p(p(M1, M2), p(M3, M4)) == q(1, 4)
- assert p(p(M4, M3), p(M2, M1)) == q(4, 1)
- print('\n'.join(output))
Advertisement
Add Comment
Please, Sign In to add comment