A1076 Forwards on Weibo (30point(s))
题意
给出所有人follow的人,然后k次查询,输入用户id,粉丝会转发该用户的微博,层次最多为L层,输出最终有多少个人转发了该微博。
思路
千万别用dfs,dfs很难不出错。该题对图的遍历深度做了限制,一些节点可能一条路走不到,但是从另一些路径可以达到,如果用dfs的话有可能会遍历不到一些节点,因为这些节点的必经之路被堵住了(vis)。
总结
多思考题意。
Sample Input:
7 3
3 2 3 4
0
2 5 6
2 3 1
2 3 4
1 4
1 5
2 2 6
Sample Output:
4
5
#include"bits/stdc++.h"
using namespace std;
const int maxn = 1010;
vector<int> nodes[1010];
int layer[maxn];
int vis[maxn];
int bfs(int id,int L){
queue<int> q;
layer[id] = 0;
q.push(id);
int res = 0;
while(!q.empty()){
int t = q.front();
q.pop();
vis[t] = 1;
int depth = layer[t];
if(depth < L){
for(int t1:nodes[t]) {
if(vis[t1]) continue;
vis[t1] = 1;
layer[t1] = depth + 1;
q.push(t1);
res ++;
}
}
}
return res;
}
int main(){
// freopen("input.txt","r",stdin);
int n,L; cin >> n >> L;
for(int i=1;i<=n;i++){
int m; scanf("%d",&m);
for(int j=0;j<m;j++){
int t; scanf("%d",&t);
nodes[t].push_back(i);
}
}
int k; cin >> k;
for(int i=0;i<k;i++){
fill(vis,vis+n+1,0);
int id; scanf("%d",&id);
cout << bfs(id,L) << endl;
}
}