样例可以过,但是为啥全WA,起点也标记了,想不通,求助
查看原帖
样例可以过,但是为啥全WA,起点也标记了,想不通,求助
389844
XjascodoixjqoinOI楼主2021/2/9 12:22
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;

const int N = 100010, M = 1000010;

int h[N], e[M], ne[M], idx;
int n, m;
bool st[N];

void add(int a, int b)
{
	e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}

void dfs(int u)
{
	cout << u << ' ';
	st[u] = true;
	vector<int> nodes;
	for (int i = h[u]; ~i; i = ne[i])
	{
		int j = e[i];
		if (!st[j]) nodes.push_back(j);
	}
	sort(nodes.begin(), nodes.end());
	for (int x : nodes)
		dfs(x);
}

void bfs()
{
	queue<int> q;
	q.push(1);
	st[1] = true;
	while (q.size())
	{
		auto t = q.front();
		q.pop();
		cout << t << ' ';
		vector<int> nodes;
		for (int i = h[t]; ~i; i = ne[i])
		{
			int j = e[i];
			if (!st[j]) nodes.push_back(j), st[j] = true;
		}
		sort(nodes.begin(), nodes.end());
		for (int x : nodes)
			q.push(x);
	}
}

int main()
{
	memset(h, -1, sizeof h);
	cin >> n >> m;
	for (int i = 0; i < m; i ++ ) 
	{
		int a, b;
		cin >> a >> b;
		add(a, b);
	}
	dfs(1);
	cout << endl;
	memset(st, 0, sizeof st);
	bfs();
	
	return 0;
}
2021/2/9 12:22
加载中...