1146. Topological Order (25)

1146. Topological Order (25)
时间限制 200 ms 内存限制 65536 kB 代码长度限制 16000 B
判题程序 Standard 作者 CHEN, Yue

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.
1146. Topological Order (25)_第1张图片
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

思路:对于给出的序列,是否为top序列,只需要满足,当前给出的节点的入度为0,则当前为止序列是合法的,并去除这个点,即将以此点为出度的边上的顶点入度减一,循环判断即可。如果出现给出的节点的入度不为0,则一定不是top排序序列
一、用两个数组保存顶点的入度,一个用于备份,一个用于临时判断使用
二、保存图,可以用邻接表的形式,也可以直接用二维数组保存图
三、每次进行判断之前,将备份数组的值赋值给临时判断数组

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
using namespace std;
const int Maxn = 1010;
int InDegree[Maxn], orinInDegree[Maxn];
vector<int> Adj[Maxn], ans;

int main() {
#ifdef _DEBUG
    freopen("data.txt", "r+", stdin);
#endif // _DEBUG

    int N,M;
    scanf("%d %d", &N, &M);
    for (int i = 0; i < M; ++i) {
        int u, v;
        scanf("%d %d", &u, &v);
        ++orinInDegree[v];
        Adj[u].push_back(v);
    }

    int Q; scanf("%d", &Q);
    for (int q = 0; q < Q; ++q){
        for (int i = 1; i <= N; ++i) {
            InDegree[i] = orinInDegree[i];
        }

        bool flag = true;
        for (int i = 0; i < N; ++i) {
            int u; scanf("%d", &u);
            if (InDegree[u] != 0) flag = false;
            for (size_t k = 0; k < Adj[u].size(); ++k) --InDegree[Adj[u][k]];
        }
        if (!flag) ans.push_back(q);
    }

    for (size_t i = 0; i < ans.size(); ++i) {
        printf("%d", ans[i]);
        if (i != ans.size() - 1) printf(" ");
    }

    return 0;
}  

你可能感兴趣的:(C/C++,OJ,pat甲级,pat甲级,1146)