using System; using static System.Console; using System.Linq; using System.Collections.Generic; class Program { static int NN => int.Parse(ReadLine()); static long[] NList => ReadLine().Split().Select(long.Parse).ToArray(); static long[][] NArr(long n) => Enumerable.Repeat(0, (int)n).Select(_ => NList).ToArray(); public static void Main() { Solve(); } static void Solve() { var c = NList; var (n, b, q) = (c[0], c[1], c[2]); var mxlist = new long[n][][]; for (var i = 0; i < n; ++i) { mxlist[i] = NArr(2); for (var j = 0; j < 2; ++j) for (var k = 0; k < 2; ++k) { mxlist[i][j][k] = (mxlist[i][j][k] % b + b) % b; } } var query = NArr(q); Matrix.mod = b; var mullist = new long[n + 1][][]; mullist[0] = new long[][] { new long[] { 1, 0 }, new long[] { 0, 1 } }; for (var i = 0; i < n; ++i) { mullist[i + 1] = Matrix.Mul(mxlist[i], mullist[i]); } var revlist = new long[n + 1][][]; revlist[0] = new long[][] { new long[] { 1, 0 }, new long[] { 0, 1 } }; for (var i = 0; i < n; ++i) { revlist[i + 1] = Matrix.Mul(revlist[i], Rev1(mxlist[i])); } var ans = new long[q][]; for (var i = 0; i < q; ++i) { var l = query[i][0]; var r = query[i][1]; var x = new long[][] { new long[] { query[i][2] }, new long[] { query[i][3] } }; var z = Matrix.Mul(Matrix.Mul(mullist[r], revlist[l]), x); ans[i] = new long[] { z[0][0], z[1][0] }; } WriteLine(string.Join("\n", ans.Select(ai => string.Join(" ", ai)))); } static long[][] Rev1(long[][] m) { return new long[][] { new long[] { m[1][1], (Matrix.mod - m[0][1]) % Matrix.mod }, new long[] { (Matrix.mod - m[1][0]) % Matrix.mod, m[0][0] }}; } class Matrix { public static long mod = 1_000_000_007; // 行列の累乗 public static long[][] Pow(long[][] m, long k) { var multi = m; var r = new long[m.Length][]; for (var i = 0; i < m.Length; ++i) { r[i] = new long[m.Length]; r[i][i] = 1; } while (k > 0) { if ((k & 1) == 1) r = Mul(r, multi); multi = Mul(multi, multi); k >>= 1; } return r; } // 行列の積 public static long[][] Mul(long[][] x, long[][] y) { var r = new long[x.Length][]; for (var i = 0; i < x.Length; ++i) r[i] = new long[y[0].Length]; for (var i = 0; i < x.Length; ++i) for (var k = 0; k < x[0].Length; ++k) { for (var j = 0; j < y[0].Length; ++j) r[i][j] = (r[i][j] + x[i][k] * y[k][j]) % mod; } return r; } } }