zoukankan      html  css  js  c++  java
  • 拓扑排序

    拓扑排序就是每次选择一个入度为0的点,然后删去该点及该点所连的边。

    拓扑排序单独出题挺少的,主要是用来优化其他算法。

    拓扑排序模版:

     1 #include <math.h>
     2 #include <stdio.h>
     3 #include <stdlib.h>
     4 #include <iostream>
     5 #include <algorithm>
     6 #include <string>
     7 #include <string.h>
     8 #include <vector>
     9 #include <map>
    10 #include <stack>
    11 #include <set>
    12 #include <queue>
    13 
    14 
    15 #define LL long long
    16 #define INF 0x3f3f3f3f
    17 #define ls nod<<1
    18 #define rs (nod<<1)+1
    19 
    20 const int maxn = 2e5 + 10;
    21 
    22 int n,m,u,v;
    23 
    24 int InDeg[maxn];
    25 std::vector<int> vec[maxn];
    26 
    27 bool topsort() {
    28     std::queue<int> q;
    29     int num = 0;
    30     for (int i=1;i<=n;i++) {
    31         if (!InDeg[i])
    32             q.push(i);
    33     }
    34     while (!q.empty()) {
    35         int now = q.front();
    36         q.pop();
    37         num++;
    38         for (int i=0;i<vec[now].size();i++) {
    39             if (--InDeg[vec[now][i]] == 0)
    40                 q.push(vec[now][i]);
    41         }
    42     }
    43     if (num == n)
    44         return true;
    45     return false;
    46 }
    47 
    48 int main() {
    49     int T;
    50     scanf("%d",&T);
    51     while (T--) {
    52         scanf("%d%d",&n,&m);
    53         for (int i=1;i<=n;i++) {
    54             vec[i].clear();
    55         }
    56         memset(InDeg,0, sizeof(InDeg));
    57         while (m--) {
    58             scanf("%d%d",&u,&v);
    59             vec[u].push_back(v);
    60             InDeg[v]++;
    61         }
    62         if (topsort())
    63             printf("Correct
    ");
    64         else
    65             printf("Wrong
    ");
    66     }
    67     return 0;
    68 }
  • 相关阅读:
    codeforces_Codeforces Round #541 (Div. 2)_abc
    小米 OJ 编程比赛 01 月常规赛_灯_找规律
    codeforces_A. Salem and Sticks_数组/暴力
    航班座位_hihocoder
    canvas
    你所必须知道的HTML
    表单及表单新增元素
    HTML5新增的结构元素
    jQuery菜单,导航与标签页
    JavaScript的DOM对象
  • 原文地址:https://www.cnblogs.com/-Ackerman/p/11979063.html
Copyright © 2011-2022 走看看