2368. 受限条件下可到达节点的数目
代码入下
class Solution {
public:
// 建图后bfs
int e[200010], h[200010], ne[200010], idx=0;//理解链表存储图的本质,h只需要开N,与节点数相同
// h[i] i的第一个临接点,通过e[h[i]]得到节点值,ne[h[i]]下一个临接点。
int st[200010];
void add (int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int reachableNodes(int n, vector<vector<int>>& edges, vector<int>& restricted) {
memset(h, -1, sizeof h);
memset(st, 0, sizeof st);
for(int i=0;i<edges.size();i++){
add(edges[i][1],edges[i][0]);
add(edges[i][0],edges[i][1]);
}
set<int> t1;
for(auto t:restricted) t1.insert(t);
//bfs
queue<int> q;
q.push(0);
int t3=0;
st[0]=1;
while(!q.empty()){
int t2=q.front();
q.pop();
cout<<t2<<endl;
if(!t1.count(t2))t3++;
for(int i=h[t2];i!=-1;i=ne[i]){
if(t1.count(e[i])){
continue;
}
if(st[e[i]]==1)continue;
st[e[i]]=1;
q.push(e[i]);
}
}
return t3;
}
};