1. 程式人生 > >Codeforces Round #397 (Div. 1 + Div. 2 combined) F.Souvenir

Codeforces Round #397 (Div. 1 + Div. 2 combined) F.Souvenir

洛谷傳送門

題目描述

Artsem is on vacation and wants to buy souvenirs for his two teammates. There are nn souvenir shops along the street. In ithi -th shop Artsem can buy one souvenir for aia_{i} dollars, and he cannot buy more than one souvenir in one shop. He doesn’t want to introduce envy in his team, so he wants to buy two souvenirs with least possible difference in price.

Artsem has visited the shopping street mm times. For some strange reason on the ithi -th day only shops with numbers from lil_{i} to rir_{i} were operating (weird? yes it is, but have you ever tried to come up with a reasonable legend for a range query problem?). For each visit, Artsem wants to know the minimum possible difference in prices of two different souvenirs he can buy in the opened shops.

In other words, for each Artsem’s visit you should find the minimum possible value of asat|a_{s}-a_{t}| where lis,tril_{i}\le s,t\le r_{i}, sts≠t .

輸入輸出格式

輸入格式:

The first line contains an integer nn (2n1052\le n\le 10^{5} ).

The second line contains nn space-separated integers a

1,...,ana_{1} , ..., a_{n}( 0ai1090\le a_{i}\le 10^{9} ).

The third line contains the number of queries mm ( 1m31051\le m\le 3·10^{5}).

Next mm lines describe the queries. ithi -th of these lines contains two space-separated integers lil_{i} and rir_{i} denoting the range of shops working on ithi -th day ( 1li<rin1\le l_{i}<r_{i}\le n ).

輸出格式:

Print the answer to each query in a separate line.

輸入輸出樣例

輸入樣例#1:

8
3 1 4 1 5 9 2 6
4
1 8
1 3
4 8
5 7

輸出樣例#1:

0
1
1
3

解題分析

考慮離線詢問, 按右端點排序, 將原來元素從左到右逐個插入線段樹, 進而修改所有右端點在RR的答案, 保證當一個詢問右端點為RR的時候, 我們剛好插入到RR的位置。線段樹每個節點維護區間[l,r][l,r]元素的有序序列, 便於查詢前驅後繼, 再記錄一個當前區間在插入到RR的時候的最優解。

不難發現, 右端點rr一定的情況下, 一個區間[l,r][l,r]的答案隨左端點ll的右移單調不減。 這是因為左端點更靠左的區間包含了靠右的區間, 這樣我們就可以記錄當前的最優解, 優先更新右區間。 如果最優解優於在當前區間能取到的最優解, 我們就沒有必要再遞迴下去更改。

考慮如何和會達到最大的複雜度: 左邊每一個點都與插入點的差小於最優解,一次更新會更新到最左邊的葉節點, 我們可以這樣構造:

...,n81,n41,n21,n,1...,\frac{n}{8}-1, \frac{n}{4}-1, \frac{n}{2}-1,n,1

...,78n+1,34n+1,12n+1,n...,\frac{7}{8}n+1,\frac{3}{4}n+1,\frac{1}{2}n+1,n

這樣構造出來的序列期望每次更新長度為log(N)log(N)個葉節點, 所以每次更新的複雜度上限為log2(N)log^2(N), 總複雜度為O(Nlog2(N)+Mlog(N))O(Nlog^2(N)+Mlog(N))

每個區間可以不用multisetmultiset維護有序的區間元素, 在建樹的時候用vectorvector記錄葉節點的元素再一路歸併上來就好了。