Problem Description
Avin is observing the cars at a crossroads. He finds that there are n cars running in the east-west direction with the i-th car passing the intersection at time ai . There are another m cars running in the north-south direction with the i-th car passing the intersection at time bi . If two cars passing the intersections at the same time, a traffic crash occurs. In order to achieve world peace and harmony, all the cars running in the north-south direction wait the same amount of integral time so that no two cars bump. You are asked the minimum waiting time.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1, 000). The second line contains n distinct integers ai (1 ≤ ai ≤ 1, 000). The third line contains m distinct integers bi (1 ≤ bi ≤ 1, 000).
Output
Print a non-negative integer denoting the minimum waiting time.
Sample Input
1 1
1
1
1 2
2
1 3
Sample Output
1
0
题目大意
Avin正在观察十字路口的车辆。他发现有n辆车在东西方向行驶,第i辆车在a[i]时间通过十字路口。另有m辆车在南北方向行驶,第i辆车在b[i]时刻通过十字路口。如果两辆车同时通过十字路口,就会发生交通事故。为了实现世界的和平与和谐,所有在南北方向行驶的汽车都要等待相同的时间,这样就不会有两辆汽车相撞。输出最短等待时间。
核心思想:
a[i]和b[i]的范围都是1~1000,
用Hash的思想改变一下a[i]数组的意义,定义其为bool类型,第i时刻有东西方向的车经过则a[i]=1,反正a[i]=0。
b[i]含义如题所述,表示南北方向的第i辆车在b[i]时刻经过路口。
第一层循环,从零升序枚举等待时间d。
第二层循环,遍历b数组,如果b[i]+d时刻有东西方向的车(即a[b[i]+d]=1)则等待时间d不符合题意,跳出第二层循环。
代码如下:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=3010;//理论上N到2000+就行
bool a[N];
int b[N];
int main()
{
int n,m,x;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(a,0,sizeof(a));
for(int i=0; i<n; i++)//处理东西方向
{
scanf("%d",&x);
a[x]=1;
}
for(int i=0; i<m; i++)//记录南北方向
scanf("%d",&b[i]);
for(int d=0;; d++)//枚举等待时间
{
int flag=0;
for(int i=0; i<m; i++)//遍历南北方向的车经过路口的时刻
if(a[b[i]+d])//撞车则不符合题意
{
flag=1;
break;
}
if(!flag)//未撞车,输出
{
printf("%d\n",d);
break;
}
}
}
return 0;
}