Advertisement
candale

Dijktra(vector/bun)

Mar 3rd, 2011
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. #include<fstream>
  2. #include<vector>
  3. #define inf 2000000000
  4. using namespace std;
  5. ifstream fin ("prog.in");
  6. ofstream fout ("prog.out");
  7. struct q
  8. {
  9. int nod, c;
  10. };
  11. vector< vector<q> > a;
  12. vector<int> d;
  13. vector<int> t;
  14. vector<bool> sel;
  15. int n;
  16. void creare()
  17. {
  18. fin>>n;
  19. a.resize(n+1);
  20. int i;
  21. q x;
  22. while(fin>>i>>x.nod>>x.c)
  23. {
  24. a[i].push_back(x);
  25. }
  26. d.resize(n+1,inf);
  27. t.resize(n+1);
  28. sel.resize(n+1);
  29. }
  30. void dijkstra(int sur)
  31. {
  32. int i,j,k,nod;
  33. sel[sur]=1;
  34. for(i=0;i<a[sur].size();i++)
  35. {
  36. d[a[sur][i].nod]=a[sur][i].c;
  37. t[a[sur][i].nod]=sur;
  38. }
  39. for(i=1;i<=n;i++)
  40. {
  41. int minn;
  42. minn=inf;
  43. for(j=1;j<=n;j++)
  44. if(sel[j]==0&&d[j]<minn)
  45. {
  46. minn=d[j];
  47. nod=j;
  48. }
  49. sel[nod]=1;
  50. for(j=0;j<a[nod].size();j++)
  51. if(sel[a[nod][j].nod]==0&&d[a[nod][j].nod]>a[nod][j].c+d[nod])
  52. {
  53. d[a[nod][j].nod]=a[nod][j].c+d[nod];
  54. t[a[nod][j].nod]=nod;
  55. }
  56. }
  57. }
  58. void afisare(int nod)
  59. {
  60. int no=t[nod];
  61. afisare(no);
  62. fout<<nod<<' ';
  63. }
  64. int main ()
  65. {
  66. creare();
  67. dijkstra(1);
  68. // afisare(5);
  69. int nod=5;
  70. while(t[nod]!=1)
  71. {
  72. fout<<nod<<' ';
  73. nod=t[nod];
  74. }
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement