拓扑排序模板

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

#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;
    }



}

 

posted @ 2020-04-03 20:10  ch_hui  阅读(197)  评论(0编辑  收藏  举报