bfs倒着遍历全是wa,正着遍历一个tle
查看原帖
bfs倒着遍历全是wa,正着遍历一个tle
978011
banfenhaohaochi6楼主2024/1/3 20:02

为什么倒着遍历后面全是wa

正着遍历就只有一个tle

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int h[N], e[N], ne[N], idx;
int n, m;
bool st[N];

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

int bfs(int x)
{
	if (x == n)
		return n;
	memset(st, 0, sizeof st);
	queue<int> q;
	q.push(x);
	int res = x;

	while (q.size())
	{
		auto t = q.front();
		q.pop();
		st[t] = true;
		res = max(res, t);
		
		for (int i = h[t]; i != -1; i = ne[i])
		{
			int j = e[i];
			if (!st[j])
				q.push(j);
		}
	}
	return res;
}

void solve()
{
	memset(h, -1, sizeof h);
	cin >> n >> m;
	while (m--)
	{
		int a, b; cin>>a>>b;
		add(a, b);
	}
	
  // 为什么倒着遍历后面全是wa
  // 正着遍历就只有一个tle
	for (int i = n; i >=1 ; --i)	
		cout << bfs(i) << " ";

}

int main()
{
	solve();
	return 0;
}
2024/1/3 20:02
加载中...