Description
坐标轴上有n个粒子,粒子坐标均为偶数,每个粒子有一个运动方向(向左或向右),速度均为1,问粒子相碰撞的最早时间,如果没有粒子会相碰则输出-1
Input
第一行一个整数n表示粒子个数,第二行n个字符(R or L)表示每个粒子的运动方向,第三行n个整数表示每个粒子的坐标xi(1<=n<=200000,0<=xi<=10^9)
Output
输出粒子相碰撞的最早时间,如果没有粒子会碰撞则输出-1
Sample Input
4
RLRL
2 4 6 10
Sample Output
1
Solution
简单题,相邻两个粒子左边的向右运动右边的向左运动才会碰撞,扫一遍更新最小值即可
Code
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 222222
int n;
char s[maxn];
struct node
{
int a;
char b;
}c[maxn];
int cmp(node x,node y)
{
return x.a<y.a;
}
int main()
{
while(~scanf("%d%s",&n,s))
{
for(int i=0;i<n;i++)scanf("%d",&c[i].a),c[i].b=s[i];
sort(c,c+n,cmp);
int ans=-1;
for(int i=0;i<n;i++)
{
if(i<n-1&&c[i].b=='R'&&c[i+1].b=='L')
{
int temp=c[i+1].a-c[i].a;
temp/=2;
if(ans==-1)ans=temp;
else ans=min(ans,temp);
}
}
printf("%d\n",ans);
}
return 0;
}