Minyou03

导航

BFS应用:拓扑排序

图论:BFS应用->拓扑排序(有向无环图)(判环算法)
拓扑排完的边的顺序都是一个方向的,可以判断一个图是否有环,如果入队元素不是n个说明一定有环,若要判断负环就需要用spfa等算法了
思路就是把每个入度为0的点插入队列,最后看一下入队元素是否有n个,是则为拓扑排序

#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define endl '\n'
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> PII;
const int P = 31;
const int INF = 0x3f3f3f3f, N = 1e5 + 5, M = 1e6 + 10;
int n, m;
int q[N], d[N];//d[i]用于记录第i个点的入度数
int h[N], e[M], ne[M], idx;
void add(int a, int b)
{
   e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
bool topsort()
{
   int hh = 0, tt = -1;
   for (int i = 1; i <= n; i++)
   {
      if (d[i] == 0)
         q[++tt] = i;
   }
   while (hh <= tt)
   {
      int t = q[hh++];
      for (int i = h[t]; i != -1; i = ne[i])
      {
         int j = e[i];
         d[j]--;
         if (d[j] == 0)
            q[++tt] = j;
      }
   }
   return tt == n - 1;
}
void solve()
{
   cin >> n >> m;
   memset(h, -1, sizeof h);
   for (int i = 0; i < m; i++)
   {
      int x, y;
      cin >> x >> y;
      add(x, y);
      d[y]++;
   }
   if (topsort())
   {
      for (int i = 0; i < n; i++)
      {
         cout << q[i] << ' ';
      }
      cout << endl;
   }
   else
      cout << '-1' << endl;
}

signed main()
{
   IOS;
   int tt = 1;
   //cin>>tt;
   while (tt--)
   {
      solve();
   }
   return 0;
}

posted on 2024-10-22 14:33  Minyou0713  阅读(11)  评论(0编辑  收藏  举报