You are given an array of N integers and Q queries. Each query is a closed interval [l, r]. You should
find the minimum absolute difference between all pairs in that interval.
Input
First line contains an integer T (T ≤ 10). T sets follow. Each set begins with an integer N (N ≤
200000). In the next line there are N integers ai (1 ≤ ai ≤ 104
), the number in the i-th cell of the
array. Next line will contain Q (Q ≤ 104
). Q lines follow, each containing two integers li
, ri (1 ≤ li
,
ri ≤ N, li < ri) describing the beginning and ending of of i-th range. Total number of queries will be
less than 15000.
Output
For the i-th query of each test output the minimum |ajak| for li ≤ j, k ≤ ri (j ̸= k) a single line.
Sample Input
1
10
1 2 4 7 11 10 8 5 1 10000
4
1 10
1 2
3 5
8 10
Sample Output
0
1
3
4
题目大概:
给出n个数,m条询问。求出l 到r 区间内任意一对数的差绝对值的最小值。
思路:
看了数据量,首先发现,数据的大小比较小。枚举一对对的数一定会超时,所以,可以枚举数的大小。而且数的大小是从最小值枚举到最大值,是排好序的,只需要算相邻的差的绝对值就好了。这样,时间复杂度就降低了不少,好像过很勉强,试一试,过了。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
const int INF=0x3f3f3f3f;
int a[maxn];
int b[maxn];
int work(int l,int r)
{
memset(b,0,sizeof(b));
int min_1=INF;
int max_1=0;
for(int i=l;i<=r;i++)
{
if(!b[a[i]])b[a[i]]++;
else return 0;
min_1=min(min_1,a[i]);
max_1=max(max_1,a[i]);
}
int pre=min_1;
//cout<<pre<<endl;
int min_2=INF;
for(int i=min_1+1;i<=max_1;i++)
{
if(b[i])
{
if(i-pre<min_2)
{
min_2=i-pre;
}
pre=i;
}
}
return min_2;
}
int main()
{
int n,m,t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&m);
while(m--)
{
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",work(l,r));
}
}
return 0;
}