-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2392.BuildAMatrixWithConditions.cpp
More file actions
68 lines (56 loc) · 1.66 KB
/
2392.BuildAMatrixWithConditions.cpp
File metadata and controls
68 lines (56 loc) · 1.66 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
59
60
61
62
63
64
65
66
67
68
class Solution {
public:
const bool resolveGraph(const vector<vector<int>>& conditions, const int k, vector<int>& order) {
// Get graph.
vector<vector<int>> graph(k + 1);
for (const vector<int>& condition : conditions)
graph[condition[0]].emplace_back(condition[1]);
// Setup calculation variables.
const int n = graph.size();
// Get offsets from above count.
vector<int> offsets(k + 1, 0);
for (int i = 0; i < n; i++)
for (const int below : graph[i])
offsets[below]++;
// Find those at top of graph.
queue<int> activeNodes;
for (int i = 1; i <= k; i++)
if (offsets[i] == 0)
activeNodes.push(i);
// Resolve order.
while (!activeNodes.empty()) {
// Get node.
const int node = activeNodes.front();
activeNodes.pop();
// Add to order.
order.push_back(node);
// Process adjacent.
for (const int below : graph[node])
if (--offsets[below] == 0)
activeNodes.push(below);
}
// Success.
return order.size() == k;
}
vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Sort into orders.
vector<int> rowOrder, colOrder;
if (!resolveGraph(rowConditions, k, rowOrder) ||
!resolveGraph(colConditions, k, colOrder)) return {};
// Remap indices.
unordered_map<int, int> rowMap(k), colMap(k);
for (int i = 0; i < k; i++) {
rowMap[rowOrder[i]] = i;
colMap[colOrder[i]] = i;
}
// Set matrix.
vector<vector<int>> result(k, vector<int>(k, 0));
for (int i = 1; i <= k; i++)
result[rowMap[i]][colMap[i]] = i;
return result;
}
};