把题目的数据看成图,进行bfs遍历即可
#include<iostream>#include<vector>#PRagma warning(disable:4996)using namespace std;int arc[1010][1010] = { 0 };//邻接矩阵int N, L;vector < bool> visited;//bfs用的int cnt;void bfs(int index,int lev)//进行遍历{ vector<int> xx; if (lev == 0) return; for (int t = 1;t <= N;t++)//先遍历完这层 if (!visited[t] && arc[index][t] == 1) { cnt++; visited[t] = true; xx.push_back(t); } for (auto x : xx)//对下层进行遍历 bfs(x, lev - 1);}int main(){ cin >> N >> L; for (int t = 1;t <= N;t++) { int temp_n; scanf("%d", &temp_n); while (temp_n--) { int temp; scanf("%d", &temp); arc[temp][t] = 1;//表示temp->t通 } } int n;cin >> n; while (n--) { int tem; scanf("%d", &tem); visited.assign(N + 1, false);//初始化数据 visited[tem] = true; cnt = 0; bfs(tem,L); printf("%d/n", cnt); }}新闻热点
疑难解答