444. Sequence Reconstruction

 2023-09-05 阅读 252 评论 0

摘要:Check whether the original sequenceorgcan be uniquely reconstructed from the sequences inseqs. Theorgsequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences

Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.

Example 1:

Input:
org: [1,2,3], seqs: [[1,2],[1,3]]Output:
falseExplanation:
[1,2,3] is not the only one sequence that can be reconstructed, because [1,3,2] is also a valid sequence that can be reconstructed.

 

Example 2:

Input:
org: [1,2,3], seqs: [[1,2]]Output:
falseExplanation:
The reconstructed sequence can only be [1,2].
class Solution {
public:bool sequenceReconstruction(vector<int>& org, vector<vector<int>>& seqs) {if (seqs.empty()) return false;int n = org.size(), cnt = n - 1;vector<int> pos(n + 1, 0), flags(n + 1, 0);bool existed = false;for (int i = 0; i < n; ++i) pos[org[i]] = i;for (auto& seq : seqs) {for (int i = 0; i < seq.size(); ++i) {existed = true;if (seq[i] <= 0 || seq[i] > n) return false;if (i == 0) continue;int pre = seq[i - 1], cur = seq[i];if (pos[pre] >= pos[cur]) return false;if (flags[cur] == 0 && pos[pre] + 1 == pos[cur]) {flags[cur] = 1; --cnt;}}}return cnt == 0 && existed;}
};

 

转载于:https://www.cnblogs.com/jxr041100/p/7885725.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/161.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息