大厂笔试题
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.

80 lines
3.1 KiB

  1. /*
  2. :
  3. A.cpp B.cpp B.cpp A.cpp 0123 011231 2,1,0,3 2,1,3,0 1,2,-1,101122312,1,0,3
  4. 1:
  5. "1,2,-1,1"
  6. 1:
  7. "2,1,0,3"
  8. */
  9. #include <bits/stdc++.h>
  10. using namespace std;
  11. class Solution {
  12. public:
  13. string compileSeq(string input) {
  14. //首先完成有向无环图的构建
  15. //统计图中各节点的个数 并标记头节点为-1
  16. //使用优先队列 按照先小后大的顺序遍历输出节点值
  17. int len = input.size();
  18. /*********构建有向无环图(指向关系)*********/
  19. map<int, vector<int>> mp;//first为先 second为后, 也就是second依赖于first
  20. string tmp;
  21. int idx = 0;
  22. for(auto& s:input){
  23. if(s != ',')
  24. tmp += s;
  25. else{
  26. mp[stoi(tmp)].push_back(idx++);
  27. string().swap(tmp);//清空string
  28. }
  29. }
  30. if(!tmp.empty())
  31. mp[stoi(tmp)].push_back(idx++);
  32. /**********统计各节点个数 并保存头节点***********/
  33. vector<int> indexcount(len, 0);//统计各节点个数
  34. priority_queue<int, vector<int>, greater<>> pq;//保存节点
  35. for(auto& m:mp){
  36. if(m.first == -1){
  37. for(auto& a:m.second){
  38. pq.push(a);
  39. indexcount[a] = -1;
  40. }
  41. }else{
  42. for(auto& a:m.second)
  43. ++indexcount[a];
  44. }
  45. }
  46. /************根据指向关系遍历图 并按照优先队列输出结果********/
  47. vector<int> ans;
  48. while(!pq.empty()){
  49. int node = pq.top();
  50. pq.pop();//输出了就需要从优先队列中弹出
  51. ans.push_back(node);
  52. for(auto& m:mp[node]){
  53. if(--indexcount[m] == 0)//如果该节点是最后一次在图中出现 则放入队列中
  54. pq.push(m);
  55. }
  56. }
  57. /***********输出结果************/
  58. string res;
  59. for(auto& i:ans){
  60. res += to_string(i);
  61. res.push_back(',');
  62. }
  63. if(!res.empty())
  64. res.pop_back();
  65. return res;
  66. }
  67. };
  68. int main(){
  69. Solution OnecompileSeq;
  70. string res = OnecompileSeq.compileSeq("1,2,-1,1");
  71. cout << res << endl;
  72. return 0;
  73. }