ZCMU 1156: 新年彩灯Ⅰ
Time Limit: 1 Sec Memory Limit: 128 MB
Description
新年将至,YY准备挂一排彩灯,已知彩灯刚挂完的彩灯共有N盏(编号为1,2,3,……),并且都是灭的。彩灯的闪烁由一段程序控制。
每一秒钟程序会生成两个正整数a和b(1<=a,b<=N),然后将编号为a和b之间的所有灯的状态改变一次,即如果灯i是灭的,那么经过一次改变,灯i会亮,如果灯i是亮的,经过一次改变,灯i会灭。
当YY看着自己挂的彩灯不断闪烁的时候,问题来了,YY想知道任意时刻某一区间灯的状态。
Input
多组测试数据,每一组第一行是一个整数N(1<=N<=1000000)和一个整数M(1<=M<=3000)。
然后是M行数据,包括以下两种形式:
1 a b 表示灯a和灯b之间的灯(含灯a和灯b)变换一次状态。
0 x y 表示YY想知道此刻灯x到灯y(包含灯x和灯y)的状态.
Output
对于每次YY想知道结果的时候,输出一行灯的状态(编号小的灯优先),如果是亮的输出”1”,否则输出”0”;
Sample Input
3 3 1 1 2 1 2 3 0 1 3
Sample Output
101
思路
看到这种什么读入一大堆区间变换最后再输出个区间状态之类的,考树状数组没跑了。这次这个是差分树状数组的区间更新+单点查询版本,全套update函数lowbit函数query函数砸上去就AC了,真的!其实有个小坑,a和b的大小关系是不确定的,需要自行判断并交换,害我WA了一次,伐开心。
AC代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <cmath>
#include <string>
#include <list>
#include <algorithm>
#include <set>
#include <list>
#include <stack>
#include <map>
#define N 1000005
#define ll long long
using namespace std;
int a[N];
int n, m;
void update(int p, int x)
{
while (p <= N) a[p] += x, p += p & -p;
}
void range_update(int l, int r, int x)
{
update(l, x);
update(r + 1, -x);
}
int query(int p)
{
int res = 0;
while (p) res += a[p], p -= p & -p;
return res;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(a, 0, sizeof(a));
for (int i = 1; i <= m; i++)
{
int ops, l, r;
scanf("%d%d%d", &ops, &l, &r);
if (l > r)swap(l, r);
if (ops)range_update(l, r, 1);
else
{
for(int j=l;j<=r;j++)
{
int t = query(j);
if (t % 2)printf("1");
else printf("0");
}
printf("\n");
}
}
}
//system("PAUSE");
return 0;
}