求数组某一段区间的最小差

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 nspace 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

2

5 3

10 2 3 12 7

0 2

0 4

2 4

2 1

1 2

0 1

Sample Output

Case 1:

1

1

4

Case 2:

1

代码:
 

#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f
#define MAXN 100100
using namespace std;
int cnt[1001];
int num[MAXN];
int kcase = 1;
void solve()
{
    int n, q;
    scanf("%d%d", &n, &q);
    for(int i = 0; i < n; i++)
        scanf("%d", &num[i]);
    printf("Case %d:\n", kcase++);
    while(q--)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        if(b - a + 1 > 1000)
            printf("0\n");
        else
        {
            memset(cnt, 0, sizeof(cnt));
            for(int i = a; i <= b; i++)
                cnt[num[i]]++;
            int pre = 0;
            int ans = INF;
            bool flag = false;
            for(int i = 1; i <= 1000; i++)
            {
                if(flag)
                    break;
                if(cnt[i] >= 2)
                {
                    flag = true;
                    break;
                }
                else if(cnt[i] == 1)
                {
                    if(pre == 0)
                        pre = i;
                    else
                    {
                        ans = min(ans, i - pre);
                        pre = i;
                    }
                }
            }
            if(flag)
                ans = 0;
            printf("%d\n", ans);
        }
    }
}
int main()
{
    int t;
    scanf("%d", &t);
    while(t--){
        solve();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/88726720
今日推荐