bfs,样例能过,但出现段错误,求助
查看原帖
bfs,样例能过,但出现段错误,求助
695872
Rinkan楼主2024/5/24 16:27
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>

using namespace std;
typedef pair<int, int>PII;
const int N = 1e5 + 10;
int e[N], ne[N], h[N], idx;
bool st[N];
int n, d;
queue<PII>q;
void add(int a, int b)
{
	e[idx] = b;
	ne[idx] = h[a];
	h[a] = idx++;
}
int bfs()
{
	int num = 0;
	q.push({ 1, 0 });
	//st[1] = true;
	while (q.size())
	{
		auto t1 = q.front().first;
		auto t2 = q.front().second;
		st[t1] = true;
		q.pop();
		if (t2 > 0 && t2 <= d) num++;
		for (int i = h[t1]; i != -1; i = ne[i])
		{
			int j = e[i];
			if (!st[j])
			{
				q.push({ j, t2 + 1 });
				//st[j] = true;
			}
		}
	}
	return num;
}
int main()
{
	memset(h, -1, sizeof(h));
	cin >> n >> d;
	for (int i = 1; i <= n - 1; i++)
	{
		int a, b;
		cin >> a >> b;
		add(a, b), add(b, a);
	}
	int res = bfs();
	cout << res << endl;
	return 0;
}
2024/5/24 16:27
加载中...