机器人碰撞

如果两个机器人发生碰撞,则将 健康度较低的机器人从路线中 移除 ,并且另一个机器人的健康度减少 1 。
幸存下来的机器人将会继续沿着与之前相同的方向前进。如果两个机器人的健康度相同,则将二者都从路线中移除

1. 单调栈

class Solution {
public:
    vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {
        int n = positions.size();
        vector<int> id(n);//存放从左往右的顺序
        iota(id.begin(),id.end(),0);
        sort(id.begin(),id.end(),[&](int i,int j){
            return positions[i]<positions[j];
        });

        stack<int> st;
        for(int i=0;i<n;i++){ //从左往右访问机器人,向左去碰,向右入栈,记录编号
            int index = id[i];//获取机器人编号
            if(directions[index]=='R')
                st.push(index);//往右走入栈
            else{//往左走,碰撞
                while(!st.empty()&&healths[index]){//有两个相反机器人存在
                    int cur = st.top();
                    if(healths[cur]<healths[index]){
                        healths[cur] = 0;
                        healths[index]--;
                        st.pop();//撞坏出栈
                    }
                    else if(healths[cur]==healths[index]){
                        healths[cur] = 0;
                        healths[index] = 0;
                        st.pop();//撞坏出栈       
                    }
                    else{
                        healths[cur]--;
                        healths[index] = 0;
                    }
                }
            }
        }
        vector<int> res;
        for(int i=0;i<n;i++)
            if(healths[i]) res.push_back(healths[i]);
        return res;
    }
};
posted @ 2023-06-28 00:29  失控D大白兔  阅读(80)  评论(0编辑  收藏  举报