Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> kahn(int src, int n, vector<vector<pair<int, int> > > &adj){
- queue<int> q;
- vector<int> indegree(n, 0);
- vector<int> order;
- for(int i = 0; i < adj.size(); i++){
- for(int j = 0; j < adj[i].size(); j++){
- int v = adj[i][j].first;
- indegree[v]++;
- }
- }
- for(int i = 0; i < n; i++){
- if(indegree[i] == 0){
- q.push(i);
- }
- }
- while(!q.empty()){
- int front = q.front();
- q.pop();
- order.push_back(front);
- for(int i = 0; i < adj[front].size(); i++){
- int node = adj[front][i].first;
- indegree[node]--;
- if(indegree[node] == 0){
- q.push(node);
- }
- }
- }
- vector<int> distance(n, INT_MIN);
- //process in topological order - guarantees that proccesing of node u, will be done after all it's prerequisites have already been processed
- //OR PROCESSED/EXPLORED all the paths that can reach u. So if all the paths are considered, whatever property was to be stored, is stored(min distance, max distance, reachability, paths(better to store predecessors tho, and track backwards to destination nodes))
- distance[src] = 0;
- for(int k = 0; k < order.size(); k++){
- int node = order[k];
- //distance from source != INT_MAX, that means it MAY or MAY NOT be able to relax an edge. But it is a possibility.
- //distance[X] = INT_MAX, these X nodes are not reachable from source, so they obviously won't be able to RELAX other nodes distances from source(Relaxation happens when nodes give a path to the source to reach other nodes at a better distance), since these X nodes are unreachable, they won't be able to give such paths(shorter/longer, here longer), simply no relaxation can't happen
- if(distance[node] != INT_MIN){
- //Relaxation possible - Try Relaxing all edges from this node
- for(int i = 0; i < adj[node].size(); i++){
- int child = adj[node][i].first, dist = adj[node][i].second;
- //found a better distance / larger distance
- distance[child] = max(distance[child], distance[node] + dist);
- }
- }
- }
- return distance;
- }
- vector<int> maximumDistance(vector<vector<int> > &edges, int n, int m, int src){
- vector<vector<pair<int, int> > > adj(n, vector<pair<int, int> >());
- for(int i = 0; i < edges.size(); i++){
- int u = edges[i][0], v = edges[i][1], w = edges[i][2];
- adj[u].emplace_back(v, w);
- }
- return kahn(src, n, adj);
- }
- int main() {
- // your code goes here
- int n, m, src;
- cin >> n >> m >> src;
- vector<vector<int> > edges(m, vector<int>(3));
- for(int i = 0; i < edges.size(); i++){
- cin >> edges[i][0] >> edges[i][1] >> edges[i][2];
- }
- vector<int> distance = maximumDistance(edges, n, m, src);
- for(int i = 0; i < distance.size(); i++){
- cout << "Node: " << i << " Distance: " << distance[i] << '\n';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment