-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_LCR_115_sequenceReconstruction.cc
More file actions
58 lines (56 loc) · 1.21 KB
/
Copy pathProblem_LCR_115_sequenceReconstruction.cc
File metadata and controls
58 lines (56 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <queue>
#include <unordered_set>
#include <vector>
using namespace std;
// @sa https://leetcode.cn/problems/sequence-reconstruction/
// @sa Problem_0444_sequenceReconstruction.cc
class Solution
{
public:
bool sequenceReconstruction(vector<int>& nums, vector<vector<int>>& sequences)
{
int n = nums.size();
vector<int> indegree(n + 1);
vector<unordered_set<int>> graph(n + 1);
for (auto& s : sequences)
{
// 为每个序列内相邻的数建立有向图
for (int i = 0; i < s.size() - 1; i++)
{
int cur = s[i];
int next = s[i + 1];
if (!graph[cur].count(next))
{
graph[cur].emplace(next);
indegree[next]++;
}
}
}
queue<int> q;
for (int i = 1; i <= n; i++)
{
if (indegree[i] == 0)
{
q.emplace(i);
}
}
while (!q.empty())
{
if (q.size() > 1)
{
// 如果队列里的元素 > 1,说明最后的拓扑结构不唯一
return false;
}
int cur = q.front();
q.pop();
for (int next : graph[cur])
{
if (--indegree[next] == 0)
{
q.emplace(next);
}
}
}
return true;
}
};