看题目这个架势,就知道要线段树,又看到维护联通块,那就得并查集。
所以,线段树维护并查集。
然而如果没想明白具体怎么写,就会gg的很惨……
首先都容易想到维护区间联通块个数和区间端点两列的点,然后就是区间合并了。
关键在于pushup,线段树是自底向上的,而并查集是自上而下的,因此,每到达一层,那么这一层的点就应该是每一个并查集的根节点,然后再考虑相邻的两个节点所在的联通块能否合并。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
#include<assert.h>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e5 + 5;
const int maxN = 1e6 + 5;
In ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
In void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
In void MYFILE()
{
#ifndef mrclr
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
#endif
}
int n, m, q, a[12][maxn];
int p[maxn * 10], cnt = 0;
In int Find(int x) {return x == p[x] ? x : p[x] = Find(p[x]);}
In bool merge(int x, int y)
{
int px = Find(x), py = Find(y);
if(px == py) return 0;
p[px] = py; return 1;
}
struct Tree
{
int l, r, sum;
int L[12], R[12];
friend In Tree operator + (Tree A, Tree B)
{
Tree ret;
ret.l = A.l, ret.r = B.r;
ret.sum = A.sum + B.sum;
for(int i = 1; i <= n; ++i)
{
p[A.L[i]] = A.L[i], p[A.R[i]] = A.R[i];
p[B.L[i]] = B.L[i], p[B.R[i]] = B.R[i];
}
for(int i = 1; i <= n; ++i)
if(a[i][A.r] == a[i][B.l]) ret.sum -= merge(A.R[i], B.L[i]);
for(int i = 1; i <= n; ++i)
ret.L[i] = Find(A.L[i]), ret.R[i] = Find(B.R[i]);
return ret;
}
}t[maxn << 2];
In void build(int L, int R, int now)
{
t[now].l = L, t[now].r = R;
if(L == R)
{
for(int i = 1; i <= n; ++i)
if(a[i][L] == a[i - 1][L]) t[now].L[i] = t[now].R[i] = t[now].L[i - 1];
else t[now].L[i] = t[now].R[i] = ++cnt, ++t[now].sum;
return;
}
int mid = (L + R) >> 1;
build(L, mid, now << 1);
build(mid + 1, R, now << 1 | 1);
t[now] = t[now << 1] + t[now << 1 | 1];
}
In Tree query(int L, int R, int now)
{
if(t[now].l == L && t[now].r == R) return t[now];
int mid = (t[now].l + t[now].r) >> 1;
if(R <= mid) return query(L, R, now << 1);
else if(L > mid) return query(L, R, now << 1 | 1);
else return query(L, mid, now << 1) + query(mid + 1, R, now << 1 | 1);
}
int main()
{
MYFILE();
n = read(), m = read(), q = read();
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= m; ++j) a[i][j] = read();
build(1, m, 1);
for(int i = 1; i <= q; ++i)
{
int L = read(), R = read();
write(query(L, R, 1).sum), enter;
}
return 0;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章