【Codeforces 793 G】—Oleg and chess(线段树优化建图+最大流)
一个很显然的扫描线
用线段树维护一下就完了
#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
static char ibuf[RLEN],*ib,*ob;
(ob==ib)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ob==ib)?EOF:*ib++;
}
#define gc getchar
inline int read(){
char ch=gc();
int res=0,f=1;
while(!isdigit(ch))f^=ch=='-',ch=gc();
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
return f?res:-res;
}
#define ll long long
#define re register
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define cs const
#define bg begin
template<class tp>inline void chemx(tp &a,tp b){a<b?a=b:0;}
template<class tp>inline void chemn(tp &a,tp b){a>b?a=b:0;}
cs int N=1000005;
cs int inf=1e9;
int n,m,tot,str,des;
struct edge{
int v,cap,r;
edge(int a=0,int b=0,int c=0):v(a),cap(b),r(c){}
};
vector<edge> e[N];
inline void addedge(int u,int v,int w){
e[u].pb(edge(v,w,e[v].size()));
e[v].pb(edge(u,0,e[u].size()-1));
}
#define It vector<edge>::iterator
namespace Flow{
int lev[N];It tp[N];
queue<int> q;
inline bool bfs(){
memset(lev,-1,sizeof(int)*(tot+1));
lev[str]=0,q.push(str);
while(!q.empty()){
int u=q.front();q.pop();
for(edge &x:e[u]){
if(lev[x.v]==-1&&x.cap>0){
lev[x.v]=lev[u]+1,q.push(x.v);
}
}
}
return lev[des]!=-1;
}
int dfs(int u,int flow){
if(u==des)return flow;
int res=0;
for(It &it=tp[u];it!=e[u].end();it++){
if(lev[it->v]==lev[u]+1&&it->cap>0){
int now=dfs(it->v,min(it->cap,flow-res));
res+=now,it->cap-=now,e[it->v][it->r].cap+=now;
if(res==flow)break;
}
}
return res;
}
inline int dinic(){
int res=0;
while(bfs()){
for(int i=1;i<=tot;i++)tp[i]=e[i].bg();
res+=dfs(str,1e9);
}
return res;
}
}
namespace Seg{
int node[N<<2],cov[N];
#define lc (u<<1)
#define rc ((u<<1)|1)
#define mid ((l+r)>>1)
inline void pushup(int u){
node[u]=++tot;
if(!cov[lc])addedge(node[u],node[lc],inf);
if(!cov[rc])addedge(node[u],node[rc],inf);
}
void build(int u,int l,int r){
if(l==r){node[u]=n+l;return;}
build(lc,l,mid),build(rc,mid+1,r);
pushup(u);
}
void update(int u,int l,int r,int st,int des,int k){
if(st<=l&&r<=des){cov[u]+=k;return;}
if(st<=mid)update(lc,l,mid,st,des,k);
if(mid<des)update(rc,mid+1,r,st,des,k);
pushup(u);
}
}
struct opt{
int l,r,op;
opt(int a=0,int b=0,int c=0):l(a),r(b),op(c){}
};
vector<opt> p[N];
int main(){
n=read(),m=read();
for(int i=1;i<=m;i++){
int x1=read(),y1=read(),x2=read(),y2=read();
p[x1].pb(opt(y1,y2,1)),p[x2+1].pb(opt(y1,y2,-1));
}
tot=2*n+2,str=2*n+1,des=str+1;
for(int i=1;i<=n;i++)addedge(str,i,1),addedge(i+n,des,1);
Seg::build(1,1,n);
for(int i=1;i<=n;i++){
opt x;
for(int j=0;j<p[i].size();j++){
x=p[i][j];
Seg::update(1,1,n,x.l,x.r,x.op);
}
if(!Seg::cov[1])addedge(i,Seg::node[1],1e9);
}
cout<<Flow::dinic();
}