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

    拓扑排序的做法因题而异,这里只有一个大概的思路及做法的模板(模板是死的,思维是活的)

    #include <iostream>
    #include <string.h>
    #include <string>
    #include <math.h>
    #include <stdlib.h>
    #include <vector>
    #include <set>
    #include <map>
    #include <queue>
    #include <stack>
    #include <bitset>
    #include <algorithm>
    #include <stdio.h>
    #include <deque>
    using namespace std;
    #define ll long long
    #define N 1000005
    #define INF 0x3f3f3f3f
    #define M 1000000007
    #define fori for(i=0;i<n;i++)
    #define fori1 for(i=1;i<=n;i++)
    const int mod = 1e9 + 7;
    ll a[N] = { 0 };
    int degree[N] = { 0 };
    vector <int> spt;//储存排序后的字符,从小到大
    vector <int> G[5];//建立邻接表
    void TopSort(vector <int> G[], int degree[]) {
        queue <int> Q;
        for (int i = 0; i < 5; i++)
            if (!degree[i])
                Q.push(i);
        while (!Q.empty()) {
            int u = Q.front();
            Q.pop();
            spt.push_back(u);
            for (int i = 0; i < G[u].size(); i++) {
                degree[G[u][i]]--;
                if (!degree[G[u][i]])
                    Q.push(G[u][i]);
            }
        }
    }
    int main()
    {
    
        ll i, j, k;
        ll n, t;
        ll sum = 0, ret = 0;
        ll ans = 0;
        ll flag = 1;
        ll x, y;
        string s[5];
        cin >> n;
        for (i = 0; i < n; i++)
        {
            cin >> x >> y;
            degree[y]++;
            G[x].push_back(y);
        }
        TopSort(G, degree);
        if (spt.size() < n)
            cout << "impossible" << endl;
        else
        {
            for (i = 0; i < spt.size(); i++)
                cout << " ";
            cout << endl;
        }
    
    
    
    }
  • 相关阅读:
    P1486 [NOI2004]郁闷的出纳员
    P1966 火柴排队
    P2627 修剪草坪
    P1621 集合
    P1025 数的划分
    中国剩余定理
    P2043 质因子分解
    P1075 质因数分解
    C#之引用类型参数
    C#之方法的定义及调用学习案例
  • 原文地址:https://www.cnblogs.com/ch-hui/p/12628672.html
Copyright © 2011-2022 走看看