Skip to content

Commit 8850563

Browse files
authored
Create 2751. Robot Collisions (#528)
2 parents 60caa79 + 278f174 commit 8850563

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

2751. Robot Collisions

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
class Solution {
2+
public:
3+
void segmentUpdate(int l,int le,int re,vector<pair<int,int>>&h){
4+
int i=le,j=le+1;
5+
while(i>=l&&j<=re){
6+
if(h[i].second==0){i--;continue;}
7+
if(h[j].second==0){j++;continue;}
8+
if(h[i].second > h[j].second){
9+
h[i].second--;h[j++].second=0;
10+
}else if(h[i].second < h[j].second){
11+
h[j].second--;h[i--].second=0;
12+
}else{
13+
h[i].second=0;i--;
14+
h[j].second=0;j++;
15+
}
16+
}
17+
}
18+
void update(vector<pair<int,int>>&h,vector<pair<int,char>>&d){
19+
int i=0;
20+
while(i<d.size()){
21+
int le=i-1,re;
22+
while(le+1<d.size()&&(h[le+1].second==0||d[le+1].second=='R'))le++;
23+
re=le;
24+
while(re+1<d.size()&&(h[re+1].second==0||d[re+1].second=='L'))re++;
25+
if(le==i-1){i=re+1;continue;}
26+
if(re==le)break;
27+
segmentUpdate(i,le,re,h);
28+
i=re+1;
29+
}
30+
}
31+
32+
bool collision(vector<pair<int,int>>&h,vector<pair<int,char>>&d){
33+
int right=d.size(),left=-1;
34+
for(int i=0;i<d.size();i++){
35+
if(h[i].second){
36+
if(d[i].second=='L')left=i;
37+
else if(right==d.size())right=i;
38+
}
39+
}
40+
return right<left;
41+
}
42+
vector<int> survivedRobotsHealths(vector<int>& po, vector<int>& he, string di) {
43+
vector<pair<int,int>>h;
44+
vector<pair<int,char>>d;
45+
for(int i=0;i<po.size();i++){
46+
h.push_back({po[i],he[i]});
47+
d.push_back({po[i],di[i]});
48+
}
49+
sort(h.begin(),h.end());
50+
sort(d.begin(),d.end());
51+
52+
while(collision(h,d))update(h,d);
53+
54+
vector<int>res(po.size());
55+
unordered_map<int,int>pos;
56+
for(int i=0;i<po.size();i++)pos[po[i]]=i;
57+
for(int j=0;j<h.size();j++){
58+
res[pos[h[j].first]]=h[j].second;
59+
}
60+
vector<int> ans;
61+
for(auto f:res)if(f)ans.push_back(f);
62+
return ans;
63+
}
64+
};

0 commit comments

Comments
 (0)