# 【GDOI2017模拟一试4.11】腐女的生日(线段树+维护一次函数)

## Code

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
const int maxn=1e5+7;
int i,j,k,l,n,m,ans,ex,ey,da,yi,er,fen;
struct nod{
int x,y,xx,yy,z;
}a[maxn*2];
bool cmp(nod x,nod y){return x.x<y.x;}
struct node{
int b1,b2;
}t[maxn*80];
void down(int x){
if(!t[x].b1&&!t[x].b2)return;
int y=x*2,z=x*2+1,u;
if(t[x].b2-t[x].b1>0)u=1;else u=-1;
t[y].b1=t[x].b1;
t[y].b2=(t[x].b1+t[x].b2+(u<0))/2;
t[z].b1=(t[x].b1+t[x].b2+(u<0))/2+u;
t[z].b2=t[x].b2;
t[x].b1=t[x].b2=0;
}
void change(int x,int l,int r,int y,int z,int xi,int sh){
if(y>z)return;
if(l==y&&r==z){
t[x].b1=xi,t[x].b2=sh;
return;
}
down(x);
int mid=(l+r)/2;
if(z<=mid)change(x*2,l,mid,y,z,xi,sh);
else if(y>mid)change(x*2+1,mid+1,r,y,z,xi,sh);
else{
int k=(xi<sh)?1:-1;
change(x*2,l,mid,y,mid,xi,xi+k*(mid-y));
change(x*2+1,mid+1,r,mid+1,z,xi+k*(mid-y+1),sh);
}
}
int find(int x,int l,int r,int y){
if(l==r)return t[x].b1;
down(x);
int mid=(l+r)/2;
if(y<=mid)return find(x*2,l,mid,y);
else return find(x*2+1,mid+1,r,y);
}
int main(){
freopen("bl.in","r",stdin);
freopen("bl.out","w",stdout);
//  freopen("fan.in","r",stdin);
da=1000001;
scanf("%d%d",&ex,&ey);ey+=da;
scanf("%d",&n);
fo(i,1,n)scanf("%d%d%d%d",&a[i].x,&a[i].y,&a[i].x,&a[i].yy),a[i].y+=da,a[i].yy+=da;
sort(a+1,a+1+n,cmp);
change(1,0,da*2,da+1,da*2,1,da);
change(1,0,da*2,0,da,da,0);
fo(i,1,n){
if(a[i].x>ex)break;
yi=find(1,0,da*2,a[i].y-1);er=find(1,0,da*2,a[i].yy+1);
fen=(a[i].y+a[i].yy-yi+er)/2;
change(1,0,da*2,a[i].y-1,fen,yi,yi+fen-a[i].y+1);
if(fen<a[i].yy)change(1,0,da*2,fen+1,a[i].yy+1,er+a[i].yy-fen,er);
}
ans=find(1,0,da*2,ey)+ex;
printf("%d\n",ans);
}