pat1146 Topological Order

题意:给一个有向图,输入一些排序,问哪一个不是拓扑排序。

思路:记录一下每个点的入度,按照给的序列遍历,每次把每次遍历到的点的入度减一,当遍历到入度不为0的点时候就说明该序列不是拓扑排序。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>

using namespace std;

const int MAX_N = 100000;

struct Data {
    int to, nxt;
}e[MAX_N];
int cnt=1, head[MAX_N];

void ins(int x, int y) {
    cnt++;
    e[cnt].to = y;
    e[cnt].nxt = head[x];
    head[x] = cnt;
}

int N, M, x, y, Q;
int ct[MAX_N];
int tmp[MAX_N];

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    scanf("%d %d", &N, &M);
    for (int i = 0; i < M; i++) {
        scanf("%d %d", &x, &y);
        ins(x, y);
        ct[y]++;
    }
    scanf("%d", &Q); bool blank = false;
    for (int i = 0; i < Q; i++) {
        int p; memcpy(tmp, ct, sizeof(ct)); bool flag = true;
        for (int k = 0; k < N; k++) {
            scanf("%d", &p);
            if (!flag) continue;
            if (tmp[p]) {
                flag = false; continue;
            }
            for (int j = head[p]; j; j = e[j].nxt) {
                tmp[e[j].to]--;
            }
        }
        if (!flag) {
            if (!blank) blank = true;
            else printf(" ");
            printf("%d", i);
        }
    }
    printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/csx0987/article/details/82081757