Advertisement
pgapr14

prim

Nov 28th, 2015
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <set>
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <queue>
  8.  
  9. #define LL long long
  10. #define ULL unsigned LL
  11. #define For(i, b) for(int i=0; i<b; i++)
  12.  
  13. using namespace std;
  14.  
  15. int val[400009], next[400009], weight[400009], last;
  16. bool vertHash[20009];
  17. priority_queue<pair<int, int> > pq_next;
  18.  
  19. void initList(int numVertex){
  20. For(i, numVertex)
  21. val[i+1] = i+1;
  22. last = numVertex+1;
  23. }
  24.  
  25. void newEdge(int v1, int v2, int w){
  26. next[val[v1]] = last;
  27. val[last] = v2;
  28. weight[last] = w;
  29. val[v1] = last;
  30. last++;
  31. }
  32.  
  33. void addEdge(int v1, int v2, int w){
  34. newEdge(v1, v2, w);
  35. newEdge(v2, v1, w);
  36. }
  37.  
  38. void markVis(int a){
  39. vertHash[a] = 1;
  40. cout<<a<<endl;
  41. }
  42.  
  43. bool vertVis(int a){
  44. return vertHash[a];
  45. }
  46.  
  47. void addNextEdges(int a){
  48. int curInd, curWeig;
  49. int nxt = next[a];
  50. while (nxt != 0){
  51. curInd = val[nxt];
  52. curWeig = weight[nxt];
  53. if(!vertVis(curInd))
  54. pq_next.push(make_pair(-1 * curWeig, curInd ));
  55. nxt = next[nxt];
  56. }
  57. }
  58.  
  59. int numVertex, numEdge;
  60.  
  61. int main(){
  62. freopen("input.in.c", "r", stdin);
  63.  
  64. cin>>numVertex>>numEdge;
  65.  
  66. initList(numVertex);
  67.  
  68. int tm1, tm2, tmw;
  69. For(i, numEdge)
  70. cin>>tm1>>tm2>>tmw, addEdge(tm1, tm2, tmw);
  71.  
  72. /*For(i, 20){
  73. cout<<i<<" "<<val[i]<<" "<<weight[i]<<" "<<next[i]<<endl;
  74. }*/
  75.  
  76. const int START_VERTEX = 1;
  77. int numTreeVert = 0;
  78. markVis(START_VERTEX);
  79. pq_next.push(make_pair(0, START_VERTEX));
  80.  
  81. while(numTreeVert < numVertex){
  82. int edgeDest = pq_next.top().second, edgeWeig=pq_next.top().first;
  83. pq_next.pop();
  84.  
  85. numTreeVert++;
  86. markVis(edgeDest);
  87. addNextEdges(edgeDest);
  88. }
  89.  
  90. return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement