Thursday, December 8, 2022

Brush (V) - LOJ-1019

 Problem: Brush (V) - LOJ-1019

Given a graph, find the shortest path from 1 to the Nth node. If its not possible to reach the last node simply print "Impossible"




#include "bits/stdc++.h"
using namespace std;


vector< pair < int, int > >adj[111];

void init(){
    for(int i = 0; i<111; i++){
        adj[i].clear();
    }
}

void dijkstra(int N){
    priority_queue< pair < int, int >, vector< pair < int, int > >, greater< pair< int, int > > > Q; 
    vectordistance(111, INT_MAX);
    vectorvisit(111, 0);
    distance[1] = 0;
    Q.push({1, 0});
    while(!Q.empty()){
        auto v = Q.top();
        Q.pop();
        int parent = v.first;
        for(auto v: adj[parent]){
            int child = v.first;
            int cost = v.second;
            if(distance[child] > distance[parent] + cost){
                distance[child] = distance[parent] + cost;
                Q.push({child,distance[child]});
            }
        }
    }
    if(distance[N] == INT_MAX)cout << "Impossible" <> N >> M;
    for(int i = 0; i < M; i++){
        int u, v, w; cin >> u >> v >> w;
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    dijkstra(N);
}
 
int main(){
    //ctrl+alt+b
    ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
    
    int T = 1; cin >> T;
    for(int __ = 1; __ <= T; __++){
        cout <<"Case "<<__<<": ";
        task();
    }
      
return 0;
}

No comments:

Post a Comment