qwerty29's blog

By qwerty29, history, 5 years ago, In English

Shortest Routes 1 on cses.

Question:
Basically print all the distances from node 1 to all other nodes. We can assume that such a path to all other nodes exists.
The path connecting the nodes is directed and weighted.

My Approach:
1) do dfs and keep updating the node's distance (initialized to LLONG_MAX at the start of search).
2) if the distance to reach a node is greater than the existing distance (previously calculated) then we don't continue the search from that node.
3) sort the edges for each node so that we choose the smallest edge every time.

My Doubt:
1) I am getting TLE for some cases. I wanted to know whether this approach is slow in general or there is some corner case that I am missing, which is getting my code to run in circles.
2) (according to me this should run

My Code:


#include <bits/stdc++.h> #define all(v) (v).begin(),(v).end() #define f first #define s second using namespace std; void dfs(int node, vector<long long int> &distance, vector<vector<pair<int,long long int> > > &graph){ for(pair<int,long long int> i:graph[node]){ if(distance[node]+i.s < distance[i.f]){ distance[i.f] = distance[node]+i.s; dfs(i.f,distance,graph); } } } bool comp(pair<int,long long int> &lhs,pair<int,long long int> &rhs){ return lhs.f < rhs.f; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n,m; cin >> n >> m; vector<vector<pair<int,long long int> > > graph(n+1); for(int i=0;i<m;++i){ int a,b; long long int c; cin >> a >> b >> c; graph[a].push_back({b,c}); } for(int i=1;i<=n;++i){ sort(all(graph[i]),comp); } vector<long long int> distance(n+1,LLONG_MAX); distance[1] = 0; dfs(1,distance,graph); for(int i=1;i<=n;++i) cout << distance[i] << ' '; cout << '\n'; return 0; }
  • Vote: I like it
  • +8
  • Vote: I do not like it

| Write comment?
»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

how about Dijkstra ?

»
5 years ago, # |
  Vote: I like it +5 Vote: I do not like it

DFS causing TLE for sure

»
5 years ago, # |
  Vote: I like it +8 Vote: I do not like it

How in the world can DFS be used to find shortest path in a weighted graph?