1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
| int n, m, q; int val[15][maxn];
struct DSU { int fa[maxn]; void init(int n) { for (int i = 0; i <= n; i++) { fa[i] = i; } } int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); } int uni(int x, int y) { x = find(x); y = find(y); if (x == y)return 0; if (x<y)swap(x, y); fa[x] = y; return 1; } }dsu; vector<int>tmp[42]; struct node { int le, ri; int ans; int col[55]; void init() { ans = 2 * n; dsu.init(2 * n); for (int i = 1; i <= n; i++) { ans -= dsu.uni(i, i + n); } for (int i = 2; i <= n; i++) { if (val[i][le] == val[i-1][le]) { ans -= dsu.uni(i, i - 1); } } for (int i = 1; i <= n; i++) { col[i] = col[i + n] = dsu.find(i); } } node operator +(const node &other) { node res; res.le = le; res.ri = other.ri;
res.ans = ans + other.ans;
for (int i = 1; i <= n; i++) { dsu.fa[i] = col[i]; dsu.fa[i + n] = col[i + n]; dsu.fa[i + 2 * n] = other.col[i] + 2 * n; dsu.fa[i + 3 * n] = other.col[i + n] + 2 * n; }
for (int i = 1; i <= n; i++) { if (val[i][ri] == val[i][other.le]) { res.ans -= dsu.uni(i + n, i + 2 * n); } } for (int i = 0; i <= 40; i++) { tmp[i].clear(); } for (int i = 1; i <= n; i++) { tmp[dsu.find(i)].push_back(i); tmp[dsu.find(i + 3 * n)].push_back(i + n); } for (int i = 0; i <= 40; i++) { for (int k = 0; k < tmp[i].size(); k++) { res.col[tmp[i][k]] = tmp[i][0]; } } return res; } }no[4 * maxn];
void build(int root, int le, int ri) { if (le == ri) { no[root].le = no[root].ri = le; no[root].init(); return; } int mid = (ri + le) / 2; build(root << 1, le, mid); build(root << 1 | 1, mid + 1, ri); no[root] = no[root << 1] + no[root << 1 | 1]; }
node query(int root, int le, int ri) { if (no[root].le == le&&no[root].ri == ri) { return no[root]; } int mid = (no[root].le + no[root].ri) / 2; if (ri <= mid)return query(root << 1, le, ri); if (le > mid)return query(root << 1 | 1, le, ri); return query(root << 1, le, mid) + query(root << 1 | 1, mid + 1, ri); }
void solve() { sa(n), sa(m), sa(q); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &val[i][j]); } } build(1, 1, m); repp(i, 1, q) { int x, y; sa(x), sa(y); node res = query(1, x, y); printf("%d\n", res.ans); } }
int main() {
solve(); return 0; }
|