-
Notifications
You must be signed in to change notification settings - Fork 0
/
Asteroid Collision.cpp
77 lines (57 loc) · 1.84 KB
/
Asteroid Collision.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
vector<int> asteroidCollision(int N, vector<int> &asteroids) {
// code here
stack<int> st;
st.push(asteroids[0]);
for(int i=1;i<N;i++){
int curr = asteroids[i];
if(curr < 0){
if(st.top() > 0){ //collide
while(!st.empty() && st.top() > 0 && abs(curr) > st.top()){
st.pop();
}
if(st.empty()){ st.push(curr);continue;}
if(st.top() > 0){
int t = st.top();
st.pop();
if(abs(curr) != t){
if(abs(curr) > t) st.push(curr);
else st.push(t);
}
}
else st.push(curr);
}
else //no collision
st.push(curr);
}else{
st.push(curr);
}
}
vector<int> answer;
while(!st.empty()) {answer.push_back(st.top()); st.pop();}
reverse(answer.begin(), answer.end());
return answer;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin >> N;
vector<int> asteroids(N);
for (int i = 0; i < N; i++) cin >> asteroids[i];
Solution obj;
vector<int> ans = obj.asteroidCollision(N, asteroids);
for (auto &it : ans) cout << it << ' ';
cout << endl;
}
return 0;
}
// } Driver Code Ends