#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 2e5 + 100;
ll T, n, k, q;
ll ans[N], cnt[N], r[N];
ll id, li, ri, v;
vector<int> a[N];
void solve() {
cin >> n >> k >> q;
for (int i = 0; i <= n; i++) ans[i] = 0, cnt[i] = 0, r[i] = 0;
for (int i = 0; i <= k; i++) a[i].clear();
for (int i = 1; i <= k; i++) {
a[i].push_back(-1);
int temp;
for (int j = 1; j <= n; j++) {
cin >> temp;
a[i].push_back(temp);
}
}
int full = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
cnt[a[j][i]]++;
if (cnt[a[j][i]] == k) full++;
}
if (full == i) r[i] = i;
}
ll p = r[n];
for (int i = n - 1; i >= 1; i--) {
if (r[i]) p = r[i];
else r[i] = p;
}
ll add = 0;
for (int i = 1; i <= n; i++) {
ans[i] = ans[i - 1] + add;
if (r[i] != i) add++;
else add = 0;
}
//for (int i = 1; i <= n; i++) printf("%d: r:%lld ans:%lld\n", i, r[i], ans[i]);
v = 0;
while (q--) {
cin >> id >> li >> ri;
id = (id + v) % k + 1, li = (li + v) % n + 1, ri = (ri + v) % n + 1;
// printf("id %lld li %lld ri %lld\n", id, li, ri);
if (r[li] < ri) v = ans[ri] - ans[r[li]];
else v = 0;
add = 0;
for (int i = li; i <= min(r[li], ri); i++) {
v += add;
add++;
}
cout << v << "\n";
}
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr), std::cout.tie(nullptr);
cin >> T;
while (T--) {
solve();
}
return 0;
}
/*
2
5 2 2
1 2 3 4 5
5 4 3 2 1
1 0 2
1 2 1
5 3 3
1 2 3 4 5
1 3 2 4 5
1 2 3 5 4
0 0 2
0 2 3
1 0 3
*/