【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
(\(1\le N\le 2\cdot 10^5\)), where the \(i\)th interval starts at position \(a_i\) on
the number line and ends at position \(b_i \geq a_i\). Both \(a_i\) and \(b_i\) are
integers in the range \(0 \ldots M\), where \(1 \leq M \leq 5000\).

To play the game, Bessie chooses some interval (say, the \(i\)th interval) and her
cousin Elsie chooses some interval (say, the \(j\)th interval, possibly the same
as Bessie's interval). Given some value \(k\), they win if
\(a_i + a_j \leq k \leq b_i + b_j\).

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

奶牛們正在努力嘗試發明有趣的新游戲來玩。他們目前的工作之一與一組 \(N\) 個區間(\(1\le N\le 2\cdot 10^5\))有關,其中第 \(i\) 個區間從數軸上的 \(a_i\) 位置開始,並在位置 \(b_i \geq a_i\) 結束。\(a_i\)\(b_i\) 均為 \(0 \ldots M\) 范圍內的整數,其中 \(1 \leq M \leq 5000\)

這個游戲的玩法是,Bessie 選擇某個區間(假設是第 \(i\) 個區間),而她的表妹 Elsie 選擇某個區間(假設是第 \(j\) 個區間,可能與 Bessie 所選的的區間相同)。給定某個值 \(k\),如果 \(a_i + a_j \leq k \leq b_i + b_j\),則她們獲勝。

對范圍 \(0 \ldots 2M\) 內的每個值 \(k\),請計算使得 Bessie 和 Elsie 可以贏得游戲的有序對 \((i,j)\) 的數量。

思路

用差分思想考慮,所有 \(a_i+a_j\) 的地方+1,所以 \(b_i+b_j+1\) 的地方減1。

然而這是 \(O(n^2)\),但我們發現 \(a,b\) 的值域很小,所以我們可以用桶存起來,然后按值域遍歷即可,就變成 \(O(m^2)\)

總結

對於一些過於重復的計算,如果值域很小,我們可以嘗試用桶存起來,減去很多過於重復的計算。

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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM