Minyou03

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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   Minyou0713  阅读(20)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示