拓撲排序 (BFS )DAG (有向無環圖)

闫柏军發表於2024-10-15

BFS

鏈式前向星

#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
int head[N];
int nxt[N];
int to[N];
int d[N];
int n;
int E = 1;
int ans[N];
int tot=1;
void add(int a, int b)
{
	//a->b;
	to[E] = b;
	nxt[E] = head[a];
	head[a] = E;
	E++;
}
void bfs()
{
	queue<int>q;
	int cnt = 0;
	for (int i = 1; i <= n; i++)
	{
		if (d[i] == 0)
		{
			q.push(i);
			cnt++;
			ans[tot++] = i;
		}
	}
	while (!q.empty())
	{
		int u = q.front();
		q.pop();
		for (int i = head[u]; i != -1; i = nxt[i])
		{
			d[to[i]]--;
			if (d[to[i]] == 0)
			{
				cnt++;
				ans[tot++] = to[i];
				q.push(to[i]);
			}
		}
	}
	if (cnt == n)
	{
		for (int i = 1; i < tot; i++)
		{
			cout << ans[i] << ' ';
		}
	}
	else
	{
		cout << -1;
	}
	return;
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	memset(head, -1, sizeof(head));
	int m;
	cin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		int x, y;
		cin >> x >> y;
		add(x, y);
		d[y]++;
	}
	bfs();
	return 0;
}

DFS待補充...

相關文章