import numpy as np n,b,q = list(map(int, input().split(' '))) mat_list = [] for i in range(n): c = list(map(int, input().split(' '))) d = list(map(int, input().split(' '))) # c = [x%b for x in c] # d = [x%b for x in c] mat_list.append(np.array([c,d])) # print(*mat_list) mat_sum = [] mat_sum.append(np.array([[1,0],[0,1]])) for i in range(n): tail = mat_sum[-1] next = np.matmul(mat_list[i],tail) next = [x%b for x in next] mat_sum.append(next) # print(*mat_sum) for _ in range(q): L,R,x,y = list(map(int, input().split(' '))) # print(L,R,x,y) total = mat_sum[R] # print(total) hosei = np.linalg.inv(mat_sum[L]) hosei = np.array(hosei,dtype='int64') # print(hosei) valid = np.matmul(hosei,total) # print(valid) target = np.array([x,y]) ans = np.matmul(valid,target) ans = [a%b for a in ans] print(*ans)