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.
题意:求区间最小差值
起初看到n和q的范围感觉会超时 但因为数的范围是[1,1000]所以直接暴力就可以
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100005],b[100005];
int vis[1005]//标记数的个数;
int main()
{
int T,t=1;
scanf("%d",&T);
while(T--)
{
int n,q;
scanf("%d%d",&n,&q);
memset(b,0,sizeof(b));
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
b[i]=a[i];
}
sort(b,b+n);
int s=unique(b,b+n)-b;//返回去重后最后一个元素的地址
printf("Case %d:\n",t++);
int x,y;
for(int i=0;i<q;i++)
{
scanf("%d%d",&x,&y);
memset(vis,0,sizeof(vis));
if(y-x>s)//如果所求区间大于不重复的个数 必有重复数字 差值为0
{
printf("0\n");
}
else
{
int ans=9999,k=-9999;
for(int j=x;j<=y;j++)
{
vis[a[j]]++;
}
for(int j=1;j<=1000;j++)
{
if(vis[j]>1)
{
ans=0;
}
if(vis[j])
{
if(ans>j-k)
{
ans=j-k;
}
k=j;
}
}
printf("%d\n",ans);
}
}
}
}