vijos 1448 校门外的树

描述

校门外有很多树,有苹果树,香蕉树,有会扔石头的,有可以吃掉补充体力的……
如今学校决定在某个时刻在某一段种上一种树,保证任一时刻不会出现两段相同种类的树,现有两个操作:
K=1,K=1,读入l、r表示在区间[l,r]中种上一种树,每次操作种的树的种类都不同
K=2,读入l,r表示询问l~r之间能见到多少种树
(l,r>0)

格式

输入格式

第一行n,m表示道路总长为n,共有m个操作
接下来m行为m个操作

输出格式

对于每个k=2输出一个答案

样例1

样例输入1

5 4
1 1 3
2 2 5
1 2 4
2 3 5

样例输出1

1
2

限制

1s

提示

范围:20%的数据保证,n,m<=100
60%的数据保证,n <=1000,m<=50000
100%的数据保证,n,m<=50000

看了题目,我们发现(其实是题解发现)如果把每种树的区间当成一个‘()’,那么【l,r】间树的种类就等于r左边‘(’的数量减去l左边‘)’的个数。然后我们就可以开两个树状数组分别存一下‘(’和‘)’的个数,在用前缀和维护就可以了。

贴一下代码

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int n,m; 
const int q = 5e4 + 3;
int t1[q],t2[q];
int lowbit(int x)
{
	return x & -x;
}
int add1(int x,int k)
{
	while(x <= n)
	{
		t1[x] += k;
		x += lowbit(x);
	}
}
int add2(int x,int k)
{
	while(x <= n)
	{
		t2[x] += k;
		x += lowbit(x);
	}
}
int sum1(int x)
{
	int t = 0;
	while(x > 0)
	{
		t += t1[x];
		x -= lowbit(x);
	}
	return t;
}
int sum2(int x)
{
	int t = 0;
	while(x > 0)
	{
		t += t2[x];
		x -= lowbit(x);
	}
	return t;
}
int main()
{
	//六年的光阴,让他们纵使恨也恨的深刻 ——德赫
	scanf("%d%d",&n,&m);
	for(int i = 1;i <= m;i++)
	{
		int op,l,r;
		scanf("%d%d%d",&op,&l,&r);
		if(op == 1)
		{
			add1(l,1);
			add2(r,1);
		}
		else
		{
			printf("%d\n",sum1(r) - sum2(l - 1));
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42914224/article/details/82952180