T - Covered Points Count (差分)

该博客探讨了一道关于计算坐标线上点被区间覆盖次数的算法题。通过输入的n个区间,要求计算每个点被覆盖1到n次的情况。作者提出使用前缀和和差分思想来解决这个问题,避免了暴力求解导致的时间复杂度过高。代码示例展示了如何通过排序和差分数组计算覆盖次数,从而高效地得出答案。
摘要由CSDN通过智能技术生成

You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.

Your task is the following: for every k∈[1…n], calculate the number of points with integer coordinates such that the number of segments that cover these points equals k. A segment with endpoints li and ri covers point x if and only if li≤x≤ri.

Input
The first line of the input contains one integer n (1≤n≤2⋅105) — the number of segments.

The next n lines contain segments. The i-th line contains a pair of integers li,ri (0≤li≤ri≤1018) — the endpoints of the i-th segment.

Output
Print n space separated integers cnt1,cnt2,…,cntn, where cnti is equal to the number of points such that the number of segments that cover these points equals to i.

Examples
Input
3
0 3
1 3
3 8

Output
6 2 1

Input
3
1 3
2 4
5 7

Output
5 2 0

Note
The picture describing the first example:

在这里插入图片描述

Points with coordinates [0,4,5,6,7,8] are covered by one segment, points [1,2] are covered by two segments and point [3] is covered by three segments.

The picture describing the second example:

在这里插入图片描述

Points [1,4,5,6,7] are covered by one segment, points [2,3] are covered by two segments and there are no points covered by three segments.

题目大意:
给出n个区间,求出在被这些区间覆盖1次、2次、3次、…、n次的个数

解题思路:
数据范围太大,暴力肯定超时的,用前缀和和差分思想可以巧妙解题,代码不长,看代码理解吧

代码:

#include<iostream>
#include<algorithm>
using namespace std;
pair<long long,long long> a[400010];	//用全局变量,栈内存是不够的 
long long n,m=0,b[200010];
int main()
{
	cin>>n;
	for(int i=0;i<n;i++){
		long long x,y;
		cin>>x>>y;
		a[m].first=x;
		a[m++].second=1;
		a[m].first=y+1;
		a[m++].second=-1;
	}
	sort(a,a+m);		//排序 
	long long d=1;
	for(int i=1;i<m;i++){
		b[d]+=a[i].first-a[i-1].first;		//差分 
		d+=a[i].second;
	}
	for(int i=1;i<=n;i++){
		if(i!=1)cout<<' ';
		cout<<b[i];
	}
	cout<<endl;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旧林墨烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值