跳到正文

题解

P1047题解

vernal_blossom约 3 分钟
原文

这是 2026年2月22日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年2月5日
收录
2026年2月22日
更新
2026年11月12日
篇幅
约 3 分钟
题目
P1047

版本

  1. v2当前
  2. v1

其他题解都没有 O(nlog⁡n)O(n \log n) 做法,所以就有了这篇题解

非常明显的线段树。区间加,区间查询。

我们把 sumsum 设置为树的数量,初始为 11 。

因为这里面赋值是赋值为 00 ,所以把懒标记设为是否赋值,为 11 时把数量赋值为 00 。

其他的就是模版。

C++
#include<bits/stdc++.h>
#define lc u<<1
#define rc u<<1|1
using namespace std;
struct node
{
	int l,r,sum,lazy;
}t[80010];
void build(int l,int r,int u)
{
	t[u].l=l;
	t[u].r=r;
	if(l==r)
	{
		t[u].sum=1;//sum为1
		return;
	}
	int mid=(l+r)/2;
	build(l,mid,lc);
	build(mid+1,r,rc);
	t[u].sum=t[lc].sum+t[rc].sum;
	return;
}
void push_down(int u)//下传
{
	if(t[u].lazy==1)//为1时赋值
	{
		t[lc].lazy=t[u].lazy;
		t[rc].lazy=t[u].lazy;
		t[lc].sum=0;
		t[rc].sum=0;
		t[u].lazy=0;
	}
}
void update(int l,int r,int u)//更新
{
	if(t[u].l>=l && t[u].r<=r)
	{
		t[u].sum=0;
		t[u].lazy=1;
		return;
	}
	push_down(u);
	int mid=(t[u].l+t[u].r)/2;
	if(l<=mid)
	{
		update(l,r,lc);
	}
	if(r>mid)
	{
		update(l,r,rc);
	}
	t[u].sum=t[lc].sum+t[rc].sum;
	return;
}
int find(int l,int r,int u)//查询
{
	push_down(u);
	if(t[u].l>=l && t[u].r<=r)
	{
		return t[u].sum;
	}
	int mid=(t[u].l+t[u].r)/2,ans=0;	
	if(l<=mid)
	{
		ans+=find(l,mid,lc);
	}
	if(r>mid)
	{
		ans+=find(mid+1,r,rc);
	}
	return ans;
}
int main()
{
	int l,m;
	cin>>l>>m;
	build(0,l,1);
	for(int i=1;i<=m;i++)
	{
		int l,r;
		cin>>l>>r;
		update(l,r,1);
	}
	cout<<find(0,l,1);
	return 0;
}