标签:
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 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).
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 |
巧妙暴力:
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 using namespace std; 7 #define mem(x,y) memset(x,y,sizeof(x)) 8 const int INF=0x3f3f3f3f; 9 const double PI=acos(-1.0); 10 const int MAXN=1e5+10; 11 int m[MAXN]; 12 int cnt[1010]; 13 void getans(int l,int r){ 14 if(r-l>=1000){//因为数字范围1-1000; 15 puts("0");return; 16 } 17 mem(cnt,0); 18 for(int i=l;i<=r;i++) 19 cnt[m[i]]++; 20 int k=-1,ans=1000; 21 for(int i=1;i<=1000;i++){ 22 if(cnt[i]>1){ 23 ans=0;break; 24 } 25 if(cnt[i]){ 26 if(k!=-1&&i-k<ans)ans=i-k; 27 k=i; 28 } 29 } 30 printf("%d\n",ans); 31 } 32 int main(){ 33 int T,n,q,flot=0; 34 scanf("%d",&T); 35 while(T--){ 36 scanf("%d%d",&n,&q); 37 for(int i=0;i<n;i++)scanf("%d",m+i); 38 printf("Case %d:\n",++flot); 39 while(q--){ 40 int l,r; 41 scanf("%d%d",&l,&r); 42 getans(l,r); 43 } 44 } 45 return 0; 46 }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/4918918.html