LightOJ 1100

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=96545#problem/E

Description:

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:

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

题意:给出一个序列,有m次查询,每次查询序列中下标为x到y之间的任意两个元素之间最小的差。

#include<stdio.h>
#include<string.h>
#include<queue>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;

const int N=1e5+10;
const int INF=0x3f3f3f3f;

int a[N], b[N]; ///b[i]用于模拟i这个数出现的次数

int main ()
{
    int T, n, m, i, Min, pre, k = 0, x, y; ///pre存放上一个可以减的数

    scanf("%d", &T);

    while (T--)
    {
        k++;

        scanf("%d%d", &n, &m);
        for (i = 0; i < n; i++)
            scanf("%d", &a[i]);

        printf("Case %d:\n", k);
        while (m--)
        {
            memset(b, 0, sizeof(b));
            pre = 0;
            Min = INF;

            scanf("%d%d", &x, &y);

            for (i = x; i <= y; i++)
                b[a[i]]++;

            for (i = 0; i <= 1000; i++)
            {
                if (!b[i]) continue;

                if (b[i] >= 2) ///如果在x~y之间一个数出现两次以上,那么该区间差的最小值就是0
                {
                    Min = 0;
                    break;
                }
                else if (b[i] == 1 && pre != 0) ///如果只出现一次,且上一次可以减的数不是0(该序列是大于1的),可以计算出一个差值
                    Min = min(Min, i-pre); ///由于两个可以相减的数是不确定的,所以每次都需要比较

                pre = i; ///更新,便于下次相减
            }

            printf("%d\n", Min);
        }
    }

    return 0;
}
posted @ 2015-10-27 12:00  搁浅の记忆  阅读(145)  评论(0编辑  收藏  举报