848. Topological Sequences of Directed Graphs

Given a directed graph with n points and m edges, the points are numbered from 1 to n, there may be multiple edges and self-loops in the graph.

Please output any topological sequence of the directed graph. If the topological sequence does not exist, output −1.

A sequence A consisting of all points in the graph is said to be a topological sequence of the graph if, for every edge (x,y) in the graph, x appears before y in A.

Input format
The first line contains two integers n and m.

The next m lines, each containing two integers x and y, indicate that there is a directed edge (x,y) from point x to point y.

Output format
A total of one line, if there is a topological sequence, just output any legal topological sequence.

Otherwise output −1.

Data range
1≤n, m≤105
Input sample:
3 3
1 2
2 3
1 3
Output sample:
1 2 3

#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int d[N], h[N], ne[N], e[N], idx;
int n, m;
int q[N];

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

int main()
{
    
    
    
    memset(h, -1, sizeof h);
    
    cin >> n >> m;
    for(int i=0; i<m; i++) {
    
    
        int a, b;
        cin >> a >> b;
        add(a, b);
        d[b]++;
    }
    
    if(topsort()) {
    
    
        for(int i=0; i<n; i++) cout << q[i] << ' ';
        cout << endl;
    }
    else cout << -1 << endl;
    
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324106484&siteId=291194637