【USACO2021 Convoluted Intervals 】题解

题目

The cows are hard at work trying to invent interesting new games to play. One of
their current endeavors involves a set of N intervals
(1N2105), where the ith interval starts at position ai on
the number line and ends at position biai. Both ai and bi are
integers in the range 0M, where 1M5000.

To play the game, Bessie chooses some interval (say, the ith interval) and her
cousin Elsie chooses some interval (say, the jth interval, possibly the same
as Bessie's interval). Given some value k, they win if
ai+ajkbi+bj.

For every value of k in the range 02M, please count the number of
ordered pairs (i,j) for which Bessie and Elsie can win the game.

奶牛们正在努力尝试发明有趣的新游戏来玩。他们目前的工作之一与一组 N 个区间(1N2105)有关,其中第 i 个区间从数轴上的 ai 位置开始,并在位置 biai 结束。aibi 均为 0M 范围内的整数,其中 1M5000

这个游戏的玩法是,Bessie 选择某个区间(假设是第 i 个区间),而她的表妹 Elsie 选择某个区间(假设是第 j 个区间,可能与 Bessie 所选的的区间相同)。给定某个值 k,如果 ai+ajkbi+bj,则她们获胜。

对范围 02M 内的每个值 k,请计算使得 Bessie 和 Elsie 可以赢得游戏的有序对 (i,j) 的数量。

思路

用差分思想考虑,所有 ai+aj 的地方+1,所以 bi+bj+1 的地方减1。

然而这是 O(n2),但我们发现 a,b 的值域很小,所以我们可以用桶存起来,然后按值域遍历即可,就变成 O(m2)

总结

对于一些过于重复的计算,如果值域很小,我们可以尝试用桶存起来,减去很多过于重复的计算。

Code

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define N 5010
int n, m, i, j, k; 
int a[N], b[N], x[N], y[N], c[N*2]; 

signed main()
{
	scanf("%lld%lld", &n, &m); 
	for(i=1; i<=n; ++i) scanf("%lld%lld", &j, &k), x[j]++, y[k]++; 
	for(i=0; i<=m; ++i)
		for(j=0; j<=m; ++j)
			c[i+j]+=x[i]*x[j], c[i+j+1]-=y[i]*y[j]; 
	for(i=k=0; i<=2*m; ++i) printf("%lld\n", k+=c[i]); 
	return 0;
}
posted @   zhangtingxi  阅读(439)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示