-
Notifications
You must be signed in to change notification settings - Fork 1
/
剑指 Offer II 115. 重建序列.cpp
41 lines (34 loc) · 1.11 KB
/
剑指 Offer II 115. 重建序列.cpp
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
class Solution {
public:
bool sequenceReconstruction(vector<int>& nums, vector<vector<int>>& sequences) {
int m = nums.size();
vector<vector<int>> graph(m+1);
vector<int> inDegree(m+1);
for (auto &edge : sequences) {
for (int i = edge.size() - 1; i > 0; --i) { //不一定只有两个元素的
int from = edge[i-1], to = edge[i];
graph[from].push_back(to); // 无权图
inDegree[to]++;
}
}
queue<int> q;
for (int i = 1; i <= m; ++i) {
if (inDegree[i] == 0) {
q.push(i);
}
}
while (q.size()) {
int size = q.size();
if (size > 1) return false;
int u = q.front(); q.pop();
for (int i = 0; i < graph[u].size(); ++i) {
int to = graph[u][i];
inDegree[to]--;
if (inDegree[to] == 0) {
q.push(i);
}
}
}
return true;
}
};