a_pramanik

BFS_weighted

Jun 11th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5.  
  6. int i,j ,k, p, x, y, src, des, n, m, z;
  7. #define mx 987654321;
  8. vector<int>a[100], co[100];
  9. queue<int>q;
  10. int vis[100];
  11. int cost[100];
  12.  
  13. int main()
  14. {
  15.  
  16. while(scanf("%d%d", &n, &m)==2){
  17.  
  18. for(i=1; i<=m; i++){
  19. scanf("%d%d%d", &x, &y, &p);
  20.  
  21. a[x].push_back(y);
  22. a[y].push_back(x);
  23. co[x].push_back(p);
  24. co[y].push_back(p);
  25. }
  26.  
  27.  
  28. scanf("%d%d",&src, &des);
  29.  
  30. q.push(src);
  31. memset(vis, -1, sizeof vis);
  32.  
  33. for(i=1; i<=n; i++)cost[i]=mx;
  34.  
  35. vis[src]=0;
  36. cost[src]=0;
  37. while(!q.empty()){
  38.  
  39. x = q.front();
  40. q.pop();
  41.  
  42. for(i=0; i <a[x].size(); i++){
  43.  
  44. y = a[x][i];
  45.  
  46. if(vis[y]==-1){
  47. vis[y]=1;
  48. cost[y]=cost[x]+co[x][i];
  49. q.push(y);
  50. }
  51. else if(cost[x]+co[x][i]<cost[y]){
  52. cost[y]=cost[x]+co[x][i];
  53. q.push(y);
  54. }
  55.  
  56.  
  57. }
  58. }
  59. printf("Minimum cost is %d\n", cost[des]);
  60.  
  61. for(i=1; i<=n; i++){
  62. a[i].clear();
  63. co[i].clear();
  64. }
  65.  
  66. }
  67. return 0;
  68. }
Add Comment
Please, Sign In to add comment