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 |
巧妙暴力:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x))
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const int MAXN=1e5+;
int m[MAXN];
int cnt[];
void getans(int l,int r){
if(r-l>=){//因为数字范围1-1000;
puts("");return;
}
mem(cnt,);
for(int i=l;i<=r;i++)
cnt[m[i]]++;
int k=-,ans=;
for(int i=;i<=;i++){
if(cnt[i]>){
ans=;break;
}
if(cnt[i]){
if(k!=-&&i-k<ans)ans=i-k;
k=i;
}
}
printf("%d\n",ans);
}
int main(){
int T,n,q,flot=;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&q);
for(int i=;i<n;i++)scanf("%d",m+i);
printf("Case %d:\n",++flot);
while(q--){
int l,r;
scanf("%d%d",&l,&r);
getans(l,r);
}
}
return ;
}
其实set写简单一些;
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x))
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const int MAXN=1e5+;
set<int>st;
int m[MAXN];
int cnt[];
void getans(int l,int r){
if(r-l>=){//因为数字范围1-1000;
puts("");return;
}
st.clear();
mem(cnt,);
for(int i=l;i<=r;i++)
st.insert(m[i]),cnt[m[i]]++;
int ans=,k=-;
set<int>::iterator iter;
for(iter=st.begin();iter!=st.end();iter++){
if(cnt[*iter]>){
ans=;break;
}
if(k!=-&&*iter-k<ans)ans=*iter-k;
k=*iter;
}
printf("%d\n",ans);
}
int main(){
int T,n,q,flot=;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&q);
for(int i=;i<n;i++)scanf("%d",m+i);
printf("Case %d:\n",++flot);
while(q--){
int l,r;
scanf("%d%d",&l,&r);
getans(l,r);
}
}
return ;
}