题意:一个圆形跑道, n n n个人跑步,每个人有不同的起始点和速度(大小和方向均可能不同),标号1-n,当两个人相遇,标号小的将会被淘汰,问最后还剩一个人时的时间。
思路:
直接模拟,首先将n个人按起点的大小排序,考虑第i个被淘汰的人,一定是与其相邻的两个人中的一个相遇,故每次可以找到最快相遇的一对选手,将其中标号小的人淘汰,模拟整个过程即可。
其中时间的最小值可用优先队列维护,细节见代码注释。
代码:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int A = 2e5 + 10;
class P{ //保存人的信息
public:
int d,v,id;
bool operator < (const P& rhs) const{
return d < rhs.d;
}
}a[A];
class G{ //优先队列维护的信息
public:
int p1,p2;
double t;
G(int _p1 = 0,int _p2 = 0,double _t = 0){
p1 = _p1,p2 = _p2,t = _t;
}
bool operator < (const G& rhs) const{
return t > rhs.t;
}
};
int L[A],R[A],n,l,all;
bool vis[A];
priority_queue<G> que;
int gcd(int x,int y){ //用于化简分数
if(y == 0) return x;
return gcd(y,x%y);
}
double Get_T(int x,int y){ //得到两个选手相遇的时间
int dx = ((a[y].d - a[x].d)%l+l)%l;
int dv = a[x].v - a[y].v;
if(dv<0){dv = -dv;dx = l - dx;}
return 1.0*dx/dv;
}
void output(int x,int y){ //输出答案
int dx = ((a[y].d - a[x].d)%l+l)%l;
int dv = a[x].v - a[y].v;
if(dv<0){dv = -dv;dx = l - dx;}
int tem = gcd(dx,dv);dx /= tem;dv /= tem;
printf("%d/%d\n",dx,dv);
}
int main(){
int T;scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&l);
for(int i=0 ;i<n ;i++) scanf("%d",&a[i].d),a[i].id = i;
for(int i=0 ;i<n ;i++) scanf("%d",&a[i].v);
sort(a,a+n);
while(que.size()) que.pop();
for(int i=0 ;i<n ;i++){
double time = Get_T(i,(i+1)%n);
que.push(G(i,(i+1)%n,time));
L[i] = ((i-1)%n+n)%n; //维护第i个选手左右的人是谁
R[i] = (i+1)%n;
}
all = n;memset(vis,0,sizeof(vis));
while(que.size()>1){
G u = que.top();que.pop();
int p1 = u.p1,p2 = u.p2;
if(vis[p1] || vis[p2]) continue; //若p1,p2之前已经被淘汰
if(L[p1] == p2 && R[p1] == p2) break;
if(a[p1].id > a[p2].id){
vis[p2] = 1; //标记被淘汰的点
R[p1] = R[p2];L[R[p2]] = p1; //更新左右情况
double time = Get_T(p1,R[p2]);que.push(G(p1,R[p2],time)); //插入新的时间
}
else{
vis[p1] = 1;
L[p2] = L[p1];R[L[p1]] = p2;
double time = Get_T(L[p1],p2);que.push(G(L[p1],p2,time));
}
if(--all <= 0) break;
}
G u = que.top();que.pop();
int p1 = u.p1,p2 = u.p2;
output(p1,p2);
}
return 0;
}