#include #include #include class Bitset { public: Bitset() { memset(bits, 0, sizeof(bits)); } Bitset(const Bitset &other) { memcpy(bits, other.bits, sizeof(bits)); } void set(int pos) { bits[pos >> 5] |= (1 << (pos & 31)); } void flip(int pos) { bits[pos >> 5] ^= (1 << (pos & 31)); } bool test(int pos) { return (bits[pos >> 5] >> (pos & 31)) & 1; } int lowbit() { for (int i = 0; i < 32; ++i) { if (!bits[i]) continue; for (int j = 0; j < 32; ++j) { if (bits[i] & (1 << j)) { bits[i] ^= (1 << j); return (i << 5) | j; } } } return -1; } Bitset &operator |=(const Bitset &other) { for (int i = 0; i < 32; ++i) bits[i] |= other.bits[i]; return *this; } Bitset &operator ^=(const Bitset &other) { for (int i = 0; i < 32; ++i) bits[i] ^= other.bits[i]; return *this; } private: unsigned bits[32]; } con[1000]; char buffer[1111]; int n; void Init() { assert(scanf("%d", &n) == 1); for (int i = 0; i < n; ++i) { con[i] = Bitset(); assert(scanf("%s", buffer) == 1); for (int j = 0; j < n; ++j) if (buffer[j] == '1') con[i].set(j); } } int GetAns(int v) { // Deal with all the vertices whose distance to v equals to d together. // now represents all the currently reachable vertices. // delta represents all the vertices whose distance to v equals to d. int ret = 0; Bitset now, delta; now.set(v); delta.set(v); for (int d = 0, pos; (pos = delta.lowbit()) != -1; ++d) { Bitset next(now); do { ret += d; next |= con[pos]; } while ((pos = delta.lowbit()) != -1); delta = next; delta ^= now; now = next; } return ret; } void Work() { int q; assert(scanf("%d", &q) == 1); while (q--) { int v, m; assert(scanf("%d%d", &v, &m) == 2); while (m--) { int x, y; assert(scanf("%d%d", &x, &y) == 2); con[x - 1].flip(y - 1); } printf("%d\n", GetAns(v - 1)); } } int main() { int cases; assert(scanf("%d", &cases) == 1); while (cases--) { Init(); Work(); } return 0; }