uva1267

该博客主要探讨了深度优先搜索(DFS)在树形结构中的应用,包括两个递归函数`dfs()`和`dfs2()`。通过输入的整数n、s和k,程序构建了一棵树并寻找特定路径。`GetResult()`函数用于计算满足条件的节点数量。内容涉及到图论、算法和数据结构的知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>


#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int maxn = 1007;
vector<int> edge[maxn],node[maxn];
int n,s,k,fa[maxn],vis[maxn];

void dfs(int cur, int father, int depth) {
	fa[cur] = father;
	if (edge[cur].size() == 1 && depth > k) {
		node[depth].push_back(cur);
	}
	for (int i = 0; i < edge[cur].size(); i++) {
		int t = edge[cur][i];
		if (t != father) dfs(t, cur, depth + 1);
	}
}

void dfs2(int cur,int father,int depth) {
	vis[cur] = true;
	int len = edge[cur].size();
	for (int i = 0; i < len; i++) {
		int t = edge[cur][i];
		if (t != father && depth < k) {
			dfs2(t, cur, depth + 1);
		}
	}
}

int GetResult() {
	memset(vis, 0, sizeof(vis));
	int ans = 0;
	for (int i = n - 1; i > k; i--) {
		for (int j = 0; j < node[i].size(); j++) {
			int t = node[i][j];
			if (vis[t])continue;
			int father = t;
			for (int l = 0; l < k; l++)father = fa[father];
			dfs2(father,-1,0);
			ans++;
		}
	}
	return ans;
}
int main()
{
	int t;
	cin >> t;
	while (t--) {
		cin >> n >> s >> k;
		for (int i = 0; i <= n; i++) {
			edge[i].clear();
			node[i].clear();
		}

		int a, b;
		for (int i = 1; i < n; i++) {
			cin >> a >> b;
			edge[a].push_back(b);
			edge[b].push_back(a);
		}
		dfs(s, -1, 0);
		cout << GetResult() << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值