1146. Topological Order (25)

This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topological order obtained from the given directed graph? Now you are supposed to write a program to test each of the options.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N (<= 1,000), the number of vertices in the graph, and M (<= 10,000), the number of directed edges. Then M lines follow, each gives the start and the end vertices of an edge. The vertices are numbered from 1 to N. After the graph, there is another positive integer K (<= 100). Then K lines of query follow, each gives a permutation of all the vertices. All the numbers in a line are separated by a space.

Output Specification:

Print in a line all the indices of queries which correspond to “NOT a topological order”. The indices start from zero. All the numbers are separated by a space, and there must no extra space at the beginning or the end of the line. It is graranteed that there is at least one answer.

Sample Input:
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


题目大意:
1 给定n个结点和m个有向边
2 给定k个序列
3 分别判断这k个序列是否为拓扑排序序列
4 输出不是拓扑排序的序列的编号, (从0开始编号)

题目思路:
根据给定的有向边,可以算出每个结点的入度,并且可以使用邻接表的方式存储每个结点能到的的结点。(当删除某结点的时候,能方便的遍历它能到达的结点,并更新这些结点的入度)

当序列满足拓扑序列时,最前面的结点的入度一定是0,当删除最前面的结点(并更新它能到达结点的入度),新的最前面的结点的入度也一定还是0。

因此判断一个序列是否是拓扑序 ,可以对序列进行遍历,并且不断更新相关结点的入度,只要遍历到某结点,但是该结点的入度不为0,则该序列不为拓扑序。

由于查询序列有多个,每次查询要将每个结点的入度恢复到初始状态,因此,我们在输入数据的时候用din1记录每个结点的入度。遍历要查询的序列的时候,可以对din2进行更新操作。每次查询完成后,对din2进行恢复,只需要把din1的值赋给din2即可。


#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;

struct Node {
    int din1; // 入度(用于初始化)
    int din2; // 入度(用于操作)
}node[1001];

void init() {
    for (int i = 1; i < 1001; i++) {
        node[i].din2 = node[i].din1;
    }
}

vector<int> v[1001]; // 记录能达到的结点
int n, m, a, b, k;
int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < m; i++) {
        scanf("%d%d", &a, &b);
        v[a].push_back(b);
        node[b].din1++;
    }
    scanf("%d", &k);
    bool isFirst = true;
    for (int x = 0; x < k; x++) {
        init();
        bool is = true;
        for (int i = 0; i < n; i++) {
            scanf("%d", &a);
            // 更新入度
            for (int j = 0; j < v[a].size(); j++) {
                node[v[a][j]].din2--;
            }
            if (node[a].din2 != 0) {
                is = false;
            }
        }
        if (is == false) {
            if (isFirst == false) printf(" ");
            isFirst = false;
            printf("%d", x);
        } 
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值