这是一道 CSP-S 第 1.5 题难度的动态规划,但是放在 CSP-J 来考严格来说也没有超纲。
S由所有人的拥有的序列首尾相接而成。- 元素
S[j]属于第person[j]个人。 - 第
i个人与第i+1个人拥有的序列在S中的分界线为end[i]。 head[round][j]表示第round轮以元素S[j]开头是否可行。tail[round][j]表示第round轮以元素S[j]结尾是否可行。headSum是第round轮中head[round]的左闭右开前缀和。owner[round][x]- 为 0 表示第
round轮没有人能以值为x的元素结尾。 - 为正整数表示第
round轮第owner[round][x]个人能以值为x的元素结尾。 - 为正无穷表示第
round轮有超过一个人能以值为x的元素结尾。
- 为 0 表示第
#include <iostream>
#include <climits>
#include <algorithm>
namespace noip {
typedef long long Int;
constexpr Int maxN = 100'000;
constexpr Int maxR = 100;
constexpr Int maxLSum = 200'000;
constexpr Int maxS = 200'000;
constexpr Int veryBeginningS = 1;
Int S[maxLSum], person[maxLSum];
bool tail[1+maxR][maxLSum], head[1+maxR][maxLSum];
Int owner[1+maxR][1+maxS];
Int n, k, q;
Int l[1+maxN], end[1+maxN];
void main() {
std::cin >> n >> k >> q;
end[0] = 0;
for (Int i = 1; i <= n; i++) {
end[i] = end[i-1]; std::cin >> l[i];
for (Int j = 1; j <= l[i]; j++) std::cin >> S[end[i]++];
for (Int j = end[i-1]; j < end[i]; j++) person[j] = i;
}
for (Int round = 1; round <= maxR; round++) {
if (round > 1)
for (Int j = 0; j < end[n]; j++) head[round][j] =
owner[round-1][S[j]] == LLONG_MAX ? true :
owner[round-1][S[j]] == 0 ? false :
owner[round-1][S[j]] != person[j];
else
for (Int j = 0; j < end[n]; j++)
head[round][j] = S[j] == veryBeginningS;
static Int headSum[1+maxLSum+1]; headSum[0] = 0; // 左闭右开
for (Int j = 0; j < end[n]; j++) headSum[j+1] = headSum[j]+head[round][j];
for (Int right = 0; right < end[n]; right++) {
Int left = std::max(end[person[right]-1], right-k+1);
tail[round][right] = headSum[right]-headSum[left];
}
std::fill(owner[round]+1, owner[round]+1+maxS, 0);
for (Int j = 0; j < end[n]; j++) if (tail[round][j]) owner[round][S[j]] =
owner[round][S[j]] == 0 ? person[j] :
owner[round][S[j]] == person[j] ? person[j] :
LLONG_MAX;
}
while (q--) {
Int r, c; std::cin >> r >> c;
std::cout << (Int)bool(owner[r][c]) << std::endl;
}
}
} int main() {
noip::Int T; std::cin >> T;
while (T--) noip::main();
return 0;
}