大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.7 KiB

  1. /*
  2. n 0 n - 1
  3. edges edges[i] = [fromi, toi] fromi toi
  4. answer answer[i] i
  5. u v u v
  6. n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]
  7. [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]
  8. - 0 1 2
  9. - 3 2 0 1
  10. - 4 2 0 2
  11. - 5 3 0 1 3
  12. - 6 5 0 1 2 3 4
  13. - 7 4 0 1 2 3
  14. */
  15. #include <bits/stdc++.h>
  16. using namespace std;
  17. class Solution {
  18. public:
  19. vector<vector<int>> getAncestors(int n, vector<vector<int>>& edges) {
  20. vector<unordered_set<int>> anc(n); // 存储每个节点祖先的辅助数组
  21. vector<vector<int>> e(n); // 邻接表
  22. vector<int> indeg(n); // 入度表
  23. // 预处理
  24. for (const auto& edge: edges) {
  25. e[edge[0]].push_back(edge[1]);
  26. ++indeg[edge[1]];
  27. }
  28. // 广度优先搜索求解拓扑排序
  29. queue<int> q;
  30. for (int i = 0; i < n; ++i) {
  31. if (!indeg[i]) {
  32. q.push(i);
  33. }
  34. }
  35. while (!q.empty()) {
  36. int u = q.front();
  37. q.pop();
  38. for (int v: e[u]) {
  39. // 更新子节点的祖先哈希表
  40. anc[v].insert(u);
  41. for (int i: anc[u]) {
  42. anc[v].insert(i);
  43. }
  44. --indeg[v];
  45. if (!indeg[v]) {
  46. q.push(v);
  47. }
  48. }
  49. }
  50. // 转化为答案数组
  51. vector<vector<int>> res(n);
  52. for (int i = 0; i < n; ++i) {
  53. for (int j: anc[i]) {
  54. res[i].push_back(j);
  55. }
  56. sort(res[i].begin(), res[i].end());
  57. }
  58. return res;
  59. }
  60. };
  61. int main(){
  62. Solution test;
  63. int n = 8;
  64. //[[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]
  65. vector<vector<int>> nums = {{0,3},{0,4},{1,3},{2,4},{2,7},{3,5},{3,6},{3,7},{4,6}};
  66. vector<vector<int>> res = test.getAncestors(n, nums);
  67. for(int i = 0; i < res.size(); i++){
  68. for(int j = 0; j < res[i].size(); j++){
  69. cout << res[i][j];
  70. }
  71. cout << endl;
  72. }
  73. return 0;
  74. }