[2020牛客算法竞赛入门课第九节习题] 签到题 线段树(水题)

题目链接:签到题

题意

中文题意不多讲了

题解

如果你真憨憨地用它给的模版,有很大可能性会T,反正我是自己写了一个线段树过的。
很明显这次我们连建树的操作都不需要了,我们所要进行的操作就是不断更新区间标记,把标记的区间答案更新然后再向上更新答案,可以用一个tree数组存储每个区间的答案,最后我们每次查询1~L的答案就是tree[1]。

代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef long double ld;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define lowbit(x) x&-x

const double PI=acos(-1.0);
const double eps=1e-6;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=2e5+10;
const int maxm=100+10;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

ll addv[maxn<<2],tree[maxn<<2];
set<pii> L;

void pushup(int p,int l,int r)
{
    
    
	if(addv[p]) tree[p]=r-l+1;
	else if(l!=r) tree[p]=tree[p*2]+tree[p*2+1];
	else tree[p]=0;
}

void add(int p,int l,int r,int addl,int addr,int v)
{
    
    
	if(addl<=l && addr>=r)
	{
    
    
		addv[p]+=v;
		int tmp=min(addv[p*2],addv[p*2+1]);
		addv[p*2]-=tmp,addv[p*2+1]-=tmp;
		addv[p]+=tmp;
		pushup(p,l,r);
		return ;
	}
	int mid=l+(r-l)/2;
	if(addl<=mid) add(p*2, l, mid, addl, addr, v);
	if(addr>mid) add(p*2+1,mid+1,r,addl,addr,v);
	pushup(p,l,r);
}

int main()
{
    
    
	ios;
	int m,n;
	cin >> m >> n;
	while(m--)
	{
    
    
		int op,l,r; cin >> op >> l >> r;
		if(op==1) 
		{
    
    
			if(L.find(mp(l,r)) != L.end()) continue;
			L.insert(mp(l,r));
			add(1, 1, n, l, r, 1);
		}
		else if(op==2) 
		{
    
    
			if(L.find(mp(l,r)) == L.end()) continue;
			L.erase(mp(l,r));
			add(1,1,n,l,r,-1);
		}
		else cout << tree[1] << endl;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44235989/article/details/108024157