LintCode-605: Sequence Reconstruction 拓扑排序经典题

这道题我感觉是LintCode里面Topological Sorting里最难Pass的,虽然思路不难,但是很多测试用例过不了。

思路:基于topological sorting。每次都要确定queue.size()是1, 并且还要判断是不是跟给出的org数组一样。否则返回false。

代码如下:

class Solution {
public:
    /** * @param org: a permutation of the integers from 1 to n * @param seqs: a list of sequences * @return: true if it can be reconstructed only one or false */
    bool sequenceReconstruction(vector<int> &org, vector<vector<int>> &seqs) {

        map<int, set<int>> neighborMap;
        map<int, int> indegreeMap;

        queue<int> q;
        if (org.empty()) {
            if (seqs.empty()) return true;
            if ((seqs.size()==1) && (seqs[0].empty())) return true;
        }

        if (org.empty() || seqs.empty() || seqs[0].empty()) 
            return false;

        for (auto v : seqs) {
            for (int i=0; i<v.size()-1; ++i) {
                //only when we find a new neighbor pair, add to the neighborMap and indegreeMap
                if (neighborMap[v[i]].find(v[i+1])==neighborMap[v[i]].end()){
                        neighborMap[v[i]].insert(v[i+1]);
                        if (indegreeMap.find(v[i+1])!=indegreeMap.end()) {
                            indegreeMap[v[i+1]]++;
                        } else {
                            indegreeMap[v[i+1]]=1;
                        }
                }
            }
        }

        int totalNum=0;
        for (int i=1; i<=org.size(); ++i) {
            if (indegreeMap[i]==0) {
                q.push(i);
            }
        }

        int index=0;
        while(q.size()==1) {
                // for (int i=0; i<q.size(); ++i) { //size should be 1, so we don't need the for loop
                int n=q.front();
                q.pop();

                if (n!=org[index++]) 
                   return false;

                for (auto i : neighborMap[n]) {
                    indegreeMap[i]--;
                    if (indegreeMap[i]==0) {
                        q.push(i);
                    }
                }
        }

        return index==org.size();
    }
};

注意输入测试例子:
1. []
[[]]
2. [5,3,2,4,1]
[[5,3,2,4],[4,1],[1],[3],[2,4],[1,1000000000]]
3. [4,1,5,2,6,3]
[[5,2,6,3],[4,1,5,2]]
4. [1,2,3]
[[1,2],[1,3],[2,3]]

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/roufoo/article/details/80537624
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞