PAT Class A 1076 (C++ can use DFS)

Test points 1 and 4 have been unable to pass. After thinking for a long time, I finally got it right.

Set a flag array to store the number of layers where dfs accesses this node. If you visit this node again, the number of layers < the value stored in the flag array means that you can traverse to subsequent nodes that have not been traversed before; if the number of layers >= the value stored in the flag array, it means that you cannot traverse the subsequent nodes that have not been traversed The nodes that have been traversed are skipped directly.

#include<iostream>
#include<unordered_set>
#include<vector>
using namespace std;
vector<vector<int>>info;
vector<int>flag;
int N, L;
int times;
unordered_set<int>temp;
void dps(int start,int q) {
	if (times == L) return;
	times++;
	for (int i = 0; i < info[start].size(); i++){
		if (info[start][i] != q && flag[info[start][i]]>times) {
			temp.insert(info[start][i]);
			flag[info[start][i]] = times;
			dps(info[start][i],q);
		}
	}
	times--;
}
int main() {
	cin >> N >> L;
	info.resize(N + 1);
	flag.resize(N + 1);
	for (int i = 1; i <= N; i++) {
		int num; cin >> num;
		for (int j = 1; j <= num; j++) {
			int up; cin >> up;
			info[up].push_back(i);
		}
	}
	int q_num; cin >> q_num;
	for (int i = 1; i <= q_num; i++) {
		int q; cin >> q;
		times = 0; temp.clear();
		fill(flag.begin(), flag.begin() + N + 1, L+1);
		dps(q,q);
		cout << temp.size() << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45681165/article/details/121090129