Avoid Sensors

https://www.careercup.com/question?id=6266160824188928

Given a room with thief on left side of the room with finite number of sensors. He has to reach on right side missing the sensors. Each sensor is placed at any random point in the room and has its coverage in the radius r. Find out if the thief can reach to the right side without touching the range of any sensor.

这道题需要用unionfind来做,思路也很清晰。要从左走到右,只要从上到下不要被隔断即可。

首先把房屋上面的sensor union起来,再把下面的sensor union起来,然后把所有的有overlap的sensor两两union起来。最后只要判断top中的任意一个sensor和bottom里任意一个sensor是否连通即可。

这道题,unionfind只要用到nodes数组的下标即可,因此可以用数组来保存parent。

class AvoidSensor{
public:
    AvoidSensor(double r_s, vector<pair<double,double>> n, double r){
        room_size = r_s;
        nodes = n;
        radius = r;
        parent.resize(n.size(),-1);
    }
    
    bool go_from_left_to_right(){
        vector<int> top, bottom;
        for (int i=0;i<nodes.size();++i){
            if (nodes[i].second+radius >= room_size)
                top.push_back(i);
            if (nodes[i].second-radius <= 0)
                bottom.push_back(i);
        }
        
        if (top.size()==0 || bottom.size()==0) return false;
        
        for (int i=0;i<top.size();++i)
            for (int j=i+1;j<top.size();++j)
                Union(top[i],top[j]);
        
        for (int i=0;i<bottom.size();++i)
            for (int j=i+1;j<bottom.size();++j)
                Union(bottom[i],bottom[j]);
        
        for (int i=0;i<nodes.size();++i){
            for (int j=i+1;j<nodes.size();++j){
                if (pow((nodes[i].first-nodes[j].first),2)+pow((nodes[i].second-nodes[j].second),2) <= pow(radius,2)){
                    Union(i,j);
                }
            }
        }    
        //for (auto x:parent) cout<<x<<' ';     
        return Find(top[0])!=Find(bottom[0]); 
    }
    
    int Find(int i){ // find the root of nodes[i]
        if (parent[i]==-1) return i;
        return parent[i] = Find(parent[i]);
    }

    void Union(int i, int j){ // union nodes[i] with nodes[j]
        int root1=Find(i);
        int root2=Find(j);
        if (root1==root2) return;
        parent[root1] = root2;
    }
    
private:
    double room_size;
    vector<pair<double,double>> nodes;
    double radius;
    
    vector<int> parent;
};


int main() {
    AvoidSensor a(1,{{0,0},{0.5,0.2},{0.7,0.4},{0.6,0.6},{1,1}},0.5);   
    cout << a.go_from_left_to_right() << endl;
    
    AvoidSensor b(1, {{0,0},{0.5,0.2},{0.7,0.4},{1,1}}, 0.5);
    cout << b.go_from_left_to_right() << endl;
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9998900.html
今日推荐