1100 - Again Array Queries
Time Limit: 3 second(s) | Memory Limit: 32 MB |
Given an array with n integers, and you are given two indices i and j (i ≠ j) in the array. You have to find two integers in the range whose difference is minimum. You have to print this value. The array is indexed from 0 to n-1.
Input
Input starts with an integer T (≤ 5), denoting the number of test cases.
Each case contains two integers n (2 ≤ n ≤ 105) and q (1 ≤ q ≤ 10000). The next line contains n space separated integers which form the array. These integers range in [1, 1000].
Each of the next q lines contains two integers i and j (0 ≤ i < j < n).
Output
For each test case, print the case number in a line. Then for each query, print the desired result.
Sample Input | Output for Sample Input |
2 5 3 10 2 3 12 7 0 2 0 4 2 4 2 1 1 2 0 1 | Case 1: 1 1 4 Case 2: 1 |
Notes
Dataset is huge, use faster I/O methods.
本来自己也是想到这样暴力了,但是没继续实施下去,后来发现一位大神暴力过了,也是醉了,果断暴力过!
比较巧妙的是利用数组的下标进行统计最近的距离,这个结合的桶排序的思想,比较巧妙........
然后就是q次暴力了......
暴力查找距离最短的时候,选一个动态参考点,就可以在1000(区间最大范围)次范围内解决....
大神们用的是什么划分树什么的,膜拜.....
#include<stdio.h>
#include<string.h>
using namespace std;
int x[100005],cnt[1005],n,m;
void slove()
{
int l,r;
scanf("%d%d",&l,&r);
if(r-l>=1000)//如果多于1000个数的话,绝对有重复的(鸽巢原理)
{
printf("0\n");
return;
}
memset(cnt,0,sizeof(cnt));
for(int i=l;i<=r;++i)//统计每个数出现的个数
{
++cnt[x[i]];
}
int kase=-1,dis=10005,tp=0;
for(int i=0;i<1005&&tp<=r-l;++i)
{
if(cnt[i]>1)//出现多于一次,绝对是 0
{
dis=0;
break;
}
if(cnt[i])//出现过的话
{
++tp;//计算统计过的个数
if(kase!=-1&&i-kase<dis)//更新最短
{
dis=i-kase;
}
kase=i;//移动参考位置
}
}
printf("%d\n",dis);
}
int main()
{
int t;
//freopen("shuju.txt","r",stdin);
scanf("%d",&t);
for(int i=1;i<=t;++i)
{
scanf("%d%d",&n,&m);
for(int j=0;j<n;++j)
{
scanf("%d",x+j);
}
printf("Case %d:\n",i);
while(m--)
{
slove();
}
}
return 0;
}