vitormartinotti

bfs01PJ

Nov 4th, 2025
979
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define pii pair<int,int>
  3. #define MAXN 100
  4.  
  5. const int INF = 1e9;
  6.  
  7. using namespace std;
  8.  
  9. vector<pii> grafo[MAXN];
  10.  
  11. int dist[MAXN];
  12.  
  13. void bfs01(int s){
  14.     deque<pii> q;
  15.     q.push_front({0,s});
  16.     dist[s] = 0;
  17.     while(!q.empty()){
  18.         pii e = q.front();
  19.         int v = e.second;
  20.         q.pop_front();
  21.         for(pii viz : grafo[v]){
  22.             int u = viz.second;
  23.             int w = viz.first;
  24.             if(dist[v]+w < dist[u]){
  25.                 dist[u] = dist[v]+w;
  26.                 if(w == 0){
  27.                     q.push_front(viz);
  28.                 }
  29.                 else{
  30.                     q.push_back(viz);
  31.                 }
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37. int main(){
  38.     int n, m; scanf("%d %d", &n, &m);
  39.    
  40.     for(int i = 0; i < m; i++){
  41.         int a, b, c; scanf("%d %d %d", &a, &b, &c); //aresta que liga a em b com custo c
  42.         grafo[a].push_back({c, b});
  43.         grafo[b].push_back({c, a});
  44.     }
  45.    
  46.     for(int i = 0; i <= n; i++){
  47.         dist[i] = INF;
  48.     }
  49.    
  50.     bfs01(1);
  51.    
  52.     printf("%d", dist[n]);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment