Gopu and the Grid Problem
Gopu is interested in the integer co-ordinates of the X-Y plane (0<=x,y<=100000). Each integer coordinate contain a lamp, initially all the lamps are in off mode. Flipping a lamp means switching it on if it is in off mode and vice versa. Maggu will ask gopu 3 type of queries.
Type 1: x l r, meaning: flip all the lamps whose x-coordinate are between l and r (both inclusive) irrespective of the y coordinate.
Type 2: y l r, meaning: flip all the lamps whose y-coordinate are between l and r (both inclusive) irrespective of the x coordinate.
Type 3: q x y X Y, meaning: count the number of lamps which are in ‘on mode’(say this number be A) and ‘off mode’ (say this number be B) in the region where x-coordinate is between x and X(both inclusive) and y-coordinate is between y and Y(both inclusive).
Input
First line contains Q-number of queries that maggu will ask to gopu. (Q <= 10^5)
Then there will be Q lines each containing a query of one of the three type described above.
Output
For each query of 3rd type you need to output a line containing one integer A.
Example
Input:
3
x 0 1
y 1 2
q 0 0 2 2
Output:
4
题意:在一个(0<=x、y<=100000)的二维平面上,对点进行操作。初始所有点的值都为0。我们可以通过一次翻转将0变成1,1变成0。现在给你n个操作,每个操作有三种可能性。
x l r,将所有x在l到r之间的点翻转
y l r,将所有y在l到r之间的点翻转
q x1 y1 x2 y2,询问在(x1,y1),(x2,y2)这两个点内的面积内有多少个点值为1
解题思路:看到区间更新第一个想到的就是线段树,然而不知道如何向下更新,于是百度了一下,才知道每次update的时候都向下更新一高度,这样就不用在询问的时候再遍历线段树了。然后最后只要算一下x1到x2,y1到y2之间有多少条值为1的边,然后与长度相乘减去重合的就行了。(注意:两个相交线的点要减两次,因为他翻转两次会变成0)
#include<cstdio>
#include<cstring>
#define maxn 111111
#define mm 100005
typedef long long ll;
ll n;
char st[5];
struct node{
ll tree[maxn<<2];
bool s[maxn<<2];
void init(){
memset(tree,0,sizeof(tree));
memset(s,0,sizeof(0));
}
void pushup(ll pos){
tree[pos]=tree[pos<<1]+tree[pos<<1|1];
}
void pushdown(ll pos,ll len)
{
if(s[pos])
{
tree[pos<<1]=len-len/2-tree[pos<<1];
tree[pos<<1|1]=len/2-tree[pos<<1|1];
s[pos<<1]^=1;
s[pos<<1|1]^=1;
s[pos]=0;
}
return;
}
void update(ll L,ll R,ll l,ll r,ll pos){
if(l>=L&&r<=R){
tree[pos]=r-l+1-tree[pos];
s[pos]^=1;
return;
}
pushdown(pos,r-l+1);
ll mid=(l+r)>>1;
if(L<=mid) update(L,R,l,mid,pos<<1);
if(R>mid) update(L,R,mid+1,r,pos<<1|1);
pushup(pos);
}
ll query(ll L,ll R,ll l,ll r,ll pos){
if(L<=l&&r<=R)return tree[pos];
int mid=(l+r)>>1;
pushdown(pos,r-l+1);
int ans=0;
if(L<=mid) ans+=query(L,R,l,mid,pos<<1);
if(R>mid) ans+=query(L,R,mid+1,r,pos<<1|1);
return ans;
}
}row,col;
ll l,r,x1,x2,y1,y2;
int main(){
scanf("%lld",&n);
for(ll i=0;i<n;i++){
scanf("%s",st);
if(st[0]=='x'){
scanf("%lld%lld",&l,&r);
l++;r++;
row.update(l,r,1,mm,1);
}
else if(st[0]=='y'){
scanf("%lld%lld",&l,&r);
l++;r++;
col.update(l,r,1,mm,1);
}
else{
scanf("%lld%lld%lld%lld",&x1,&y1,&x2,&y2);
x1++;x2++;y1++;y2++;
ll a1=row.query(x1,x2,1,mm,1);
ll a2=col.query(y1,y2,1,mm,1);
ll ans=a1*(y2-y1+1)+a2*(x2-x1+1)-2*a1*a2;
printf("%lld\n",ans);
}
}
return 0;
}