lightOJ 1100 【巧妙暴力】

E - 楼下水题
Time Limit: 3000MS      Memory Limit: 32768KB      64bit IO Format: %lld & %llu

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


思路:


          一开始我是用sort排序然后让挨着的两个做差,找差的最小值,但是提交后超时!但是在看过别人的代码后,我学会了一中巧妙的方法,那就是不用排序,先判断输入数的个数是否超过给定的数的个数,如果超过给定的数的个数,那么肯定要有重复的数,那么最小的两个数的差就为0 ,否则的话就在1到1000的范围内进行遍历,看看那个数在这组数(从u到v的范围内)内出现的次数,如果有大于1次的直接给dis赋值为0(不能直接输出0,如果直接输出0,在下面还有一个输出语句那么会有两个输出,造成出错),否则的话,就看看那个数是不是第一个出现在u到v的范围内的第一个数(通过判断flag是否为-1),如果是第一个数的话,就将flag赋值为i,dis不变,但是当不是第一个数的话,就将dis进行更新,flag也更近!


代码:


#include <stdio.h>
#include <string.h>
int T;
int n,q;
int a[100005];
int num[1005];
int min(int a,int b)
{
	if(a<b)
		return a;
	else
		return b;
}
int main()
{
	int N;
	scanf("%d",&T);
	N=T;
	while(T--)
	{
		memset(num,0,sizeof(num));
		scanf("%d%d",&n,&q);
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
		}
		printf("Case %d:\n",N-T);
		while(q--)
		{
			int u,v;
			scanf("%d%d",&u,&v);
			if(v-u>=1000)
			{
				printf("0\n");
				continue;
			}
			memset(num,0,sizeof(num));
			for(int i=u;i<=v;i++)
			{
				num[a[i]]++;
			}
			int dis=1005,flag=-1,t=0;
			for(int i=1;i<=1000&&t<=v-u;i++)
			{
				if(num[i]>1)
				{
					dis=0;
					break;
				}
				else if(num[i]==1)
				{
					t++;
					if(flag==-1)
					{
						flag=i;
					}
					else
					{
						dis=min(dis,i-flag);
						flag=i;
					}
				}
			}
			printf("%d\n",dis);
		}
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值