8.前缀和与差分

二维差分+二维前缀和

二维前缀和:

pre[i][j] = a[i][j]。。。。bulabula有空再补⑧

练习

E - Covered Points Count(差分+前缀和+离散化)⭐⭐

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
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.
题目大意:
输入区间,输出被覆盖次数为1、2、…n的点的个数。
思路:
可以看出这道题l和r的值是很大的,如果还和普通的前缀和一样去直接一个点一个点遍历的话,就会在很多被覆盖次数为0的点处浪费时间空间,所以可以考虑离散化+差分+前缀和的思想。
可以建立一个map存放所有端点和差分,两个相邻端点间(左闭右开)的点的被覆盖次数一定相同,被覆盖次数可以通过前缀和求出来,点数直接端点坐标相减即可。
AC代码:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
typedef long long ll;
const ll N=2e5+10;
int n;
ll l,r;
map<ll,int> mp;	//key对应坐标,value对应前缀
//map会自动将key值排序 
ll cnt[N];
int main()
{
	scanf("%d",&n);
	int k=n;
	while(k--)
	{
		scanf("%lld%lld",&l,&r);
		mp[l]++;
		mp[r+1]--;
	}
	map<ll,int>::iterator it=mp.begin();
	int ans=it->second;
	ll last=it->first;
	for(it++;it!=mp.end();it++)
	{
		cnt[ans]+=it->first-last;	//两端点的坐标差,表示两端点覆盖的点数,左闭右开
									//从左端点到下一个端点前被覆盖次数都与左端点是相同的 
		last=it->first;
		ans+=it->second;	//前缀和 ,表示被覆盖了几次 
	}
	printf("%lld",cnt[1]);
	for(int i=2;i<=n;i++)
		printf(" %lld",cnt[i]);
	return 0;
}
/* 
差分: 
0 1 2 3  4 5 6 7 8  9
1 1 0 1 -2 0 0 0 0 -1

存mp 
0 1 3  4  9
1 1 1 -2 -1

前缀和 
0 1 3 4 9
1 2 3 1 0
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值