1146 Topological Order (25 point(s))

思路:

按照给定序列,如果是拓扑序列,那么就输出序号,序号从 0 开始。

1146 Topological Order (25 point(s))

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.

gre.jpg

Example:

#include<iostream>
#include<vector>
#include<unordered_set>
#include<vector>
using namespace std;

struct Graph {
    int Nv;
    int Ne;
    vector<unordered_set<int>> in;
    vector<unordered_set<int>> out;
};

bool isTopological(Graph G, vector<int> &ans)
{
    for(auto &x : ans) {
        if(!G.in[x].empty()) return false;
        for(auto y : G.out[x]) G.in[y].erase(x);
    }
    return true;
}

int main()
{
    int  N, M, K;
    cin >> N >> M;
    Graph G;
    G.Nv = N, G.Ne = M, G.in.resize(N+1), G.out.resize(N+1);
    for(int i = 0 ; i < M; i++) {
        int v1, v2;
        cin >> v1 >> v2;
        G.out[v1].insert(v2), G.in[v2].insert(v1);
    }
    cin >> K;
    vector<int> ans;
    for(int i = 0; i < K; i++) {
        vector<int> tmp(N);
        for(int k = 0; k < N; k++) cin >> tmp[k];
        if(!isTopological(G, tmp)) ans.push_back(i);
    }
    for(auto x = ans.begin(); x != ans.end(); x++)
        cout<< (x == ans.begin() ? "" : " ") << *x ;
}

猜你喜欢

转载自blog.csdn.net/u012571715/article/details/114674623