#865. 喵~喵~喵~

题目链接

#865. 喵喵~

\(C\) 养了 \(n\) 只猫,编号从 \(1-n\) 。小 \(C\) 不喜欢一次只给一头猫喂猫粮,因此他选择一下喂很多只编号连续的猫,并且每次喂的猫粮都是不同种类的。现在有 \(m\) 次操作,每 次操作给定 \(o p, l, r\)

  • \(o p=1\) ,代表小 \(C\) 会给编号为 \([l, r]\) 的猫进行一次投喂。
  • \(o p=2\) ,代表一次询问,请你回答出编号为 \([l, r]\) 的所有猫一共吃到了多少种猫粮。

输入格式

第一行两个数字 \(n, m\)
接下来有 \(m\) 行,每行 \(3\) 个整数 \(o p, l, r\)

输出格式

对于每次询问,请输出 \(1\) 行一个整数表示答案。

样例输入

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

样例输出

1
2

数据规模

所有数据保证 \(0 \leq n, m \leq 100000,1 \leq l \leq r \leq n\)

解题思路

树状数组

即给出多种线段,每次询问一个区间内有多少条线段与其有交集,直接做不好做,考虑与其没有交集的线段,即对于一个区间 \([l,r]\),之间出现的线段为 \([l_i,r_i]\),即找有多少条线段的 \(r_i\) 小于 \(l\),有多少条线段的 \(l_i\) 大于 \(r\),拿树状数组统计即可

  • 时间复杂度:\(O(mlogn)\)

代码

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=1e5+5;
int tr1[N],tr2[N];
int n,m,op,l,r;
void add1(int x,int y)
{
	for(;x<N;x+=x&-x)tr1[x]+=y;
}
void add2(int x,int y)
{
	for(;x<N;x+=x&-x)tr2[x]+=y;
}
int ask1(int x)
{
	int res=0;
	for(;x;x-=x&-x)res+=tr1[x];
	return res;
}
int ask2(int x)
{
	int res=0;
	for(;x;x-=x&-x)res+=tr2[x];
	return res;
}
int main()
{
    help;
    cin>>n>>m;
    int t=0;
    while(m--)
    {
    	cin>>op>>l>>r;
    	if(op==1)add1(l,1),add2(r,1),t++;
    	else
    		cout<<t-(t-ask1(r))-ask2(l-1)<<'\n';
    }
    return 0;
}
posted @ 2022-05-09 18:52  zyy2001  阅读(25)  评论(0编辑  收藏  举报