Vladik and Entertaining Flags CodeForces - 811E (并查集,线段树)

用线段树维护每一块左右两侧的并查集, 同色合并时若不连通则连通块数-1, 否则不变

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
//head const int N = 1e5+10;
int n, m, q;
int fa[44], vis[44], a[11][N];
int Find(int x) {return fa[x]==x?x:fa[x]=Find(fa[x]);} struct _ {
int l, r, v, L[11], R[11];
_ operator + (const _ & rhs) const {
_ ret;
ret.l = l, ret.r=rhs.r;
ret.v = v+rhs.v;
REP(i,1,n) {
fa[i]=L[i];
fa[i+n]=R[i];
fa[i+2*n]=rhs.L[i]+n*2;
fa[i+3*n]=rhs.R[i]+n*2;
}
REP(i,1,n) if (a[i][r]==a[i][rhs.l]) {
int x=Find(i+n), y=Find(i+n*2);
if (x!=y) fa[y]=x, --ret.v;
}
memset(vis,0,sizeof vis);
REP(i,1,n) {
if (!vis[Find(i)]) vis[Find(i)]=ret.L[i]=i;
else ret.L[i]=vis[Find(i)];
if (!vis[Find(i+3*n)]) vis[Find(i+3*n)]=ret.R[i]=i+n;
else ret.R[i]=vis[Find(i+3*n)];
}
return ret;
}
} tr[N<<2]; void build(int o, int l, int r) {
if (l==r) {
tr[o].l=tr[o].r=l;
REP(i,1,n) {
if (a[i][l]==a[i-1][l]) tr[o].L[i]=tr[o].R[i]=tr[o].L[i-1];
else tr[o].L[i]=tr[o].R[i]=i,++tr[o].v;
}
return;
}
build(ls), build(rs);
tr[o]=tr[lc]+tr[rc];
}
_ query(int o, int l, int r, int ql, int qr) {
if (ql<=l&&r<=qr) return tr[o];
if (mid>=qr) return query(ls,ql,qr);
if (mid<ql) return query(rs,ql,qr);
return query(ls,ql,qr)+query(rs,ql,qr);
} int main() {
scanf("%d%d%d", &n, &m, &q);
REP(i,1,n) REP(j,1,m) scanf("%d", &a[i][j]);
build(1,1,m);
REP(i,1,q) {
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n",query(1,1,m,l,r).v);
}
}
上一篇:mysql忘记root密码连接本地库


下一篇:OCA读书笔记(4) - 管理数据库实例