PAT Class A 1146 Topological Order

Link to original title

Here is a question given in the 2018 Graduate Entrance Examination:

Which of the following options is not a topological sequence obtained from a given directed graph?

Now, write a program to test each option.

Input Format
The first line contains two integers N and M, respectively representing the number of vertices and edges of the directed graph.

Next M lines, each line gives the start and end of an edge.

Points are numbered from 1 to N.

Another line contains an integer K, indicating the number of queries.

Next K lines, each line contains a permutation of all points.

Numbers on a line are separated by spaces.

Output Format
Output the numbers of all query sequences that are not topological sequences on one line.

Query sequence numbers start at 0.

There must be no extra spaces at the beginning and end of the line, and at least one solution is guaranteed to exist.

Data range
1≤N≤1000,
1≤M≤10000,
1≤K≤100
Input example:
6 8
1 2
1 3
5 2
5 4
2 3
2
6 3
4
6
4 5 1 5 2 3 6 4
5 1 2 6 3 4
5 1 2 3 6 4
5 2 1 6 3 4
1 2 3 4 5 6
Sample output:
3 4

My solution:

#include <bits/stdc++.h>
using namespace std;
const int N = 1010, M = 10010;
struct Edge{
    int a, b;
}e[M];
int p[N];
int n, m;
int main(){
    cin >> n >> m;
    for(int i = 0; i < m; i ++ ){
        cin >> e[i].a >> e[i].b;
    }
    int k;
    cin >> k;
    bool is_first = true;
    for(int i = 0; i < k; i ++ ){
        for(int j = 1; j <= n; j ++ ){
            int x;
            cin >> x;
            p[x] = j;
        }
        bool success = true;
        for(int v = 0; v < m; v ++ ){
            if(p[e[v].a] > p[e[v].b]){
                success = false;
                break;
            }
        }
        if(!success){
            if(is_first) is_first = false;
            else cout << " ";
            cout << i;
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45660485/article/details/126046389
Recommended