E. Grid
大意: 给定$n\cdot m$个点的图, 初始无边, $q$个操作, $(1,a,b)$表示第$a$列到第$b$列全连起来, $(2,a,b)$表示把第$a$行到第$b$行全连起来, 每次操作后输出连通块个数.
直接用$set$暴力模拟即可.
还有一种线段树做法, 设一共$a$行连通, $b$列连通, 可以发现答案是$nm-a(m-1)-b(n-1)+max(0,(a-1)(b-1))$, 可以用线段树维护$a$和$b$即可
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <cmath> #include <set> #include <map> #include <queue> #include <string> #include <cstring> #include <bitset> #include <functional> #include <random> #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' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<',';hr;}) 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;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head int n,m,q; struct _ { int l,r; bool operator < (const _ &rhs) const { return l<rhs.l; } }; set<_> A,B; //A为行 //B为列 int main() { while (~scanf("%d%d%d", &n, &m, &q)) { A.clear(),B.clear(); ll ans = (ll)n*m, suma = 0, sumb = 0; while (q--) { int op,l,r; scanf("%d%d%d",&op,&l,&r); if (op==1) { auto p = A.lower_bound({l,0}); if (p!=A.begin()&&(--p)->r>=l) l = p->l; while (1) { p = A.lower_bound({l,0}); if (p==A.end()||p->l>r) break; r = max(r, p->r); ans += (p->r-p->l+1ll)*(m-(B.empty()?1:sumb)); suma -= p->r-p->l+1; A.erase(p); if (B.size()&&A.empty()) ans += sumb-1; } suma += r-l+1; ans -= (r-l+1ll)*(m-(B.empty()?1:sumb)); if (B.size()&&A.empty()) ans -= sumb-1; A.insert({l,r}); } else { auto p = B.lower_bound({l,0}); if (p!=B.begin()&&(--p)->r>=l) l = p->l; while (1) { p = B.lower_bound({l,0}); if (p==B.end()||p->l>r) break; r = max(r, p->r); ans += (p->r-p->l+1ll)*(n-(A.empty()?1:suma)); sumb -= p->r-p->l+1; B.erase(p); if (A.size()&&B.empty()) ans += suma-1; } sumb += r-l+1; ans -= (r-l+1ll)*(n-(A.empty()?1:suma)); if (A.size()&&B.empty()) ans -= suma-1; B.insert({l,r}); } printf("%lld\n",ans); } } }