Network Delay Time-leetcode
Topic:
There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (U, V, W), where you are the source node, V is the target no De, and W is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K. How long would it take for all nodes to receive the signal? If It is impossible, return-1.
Test before a problem, just test test, but did not print out.
The title will give a picture of the edge weights, and then give a starting point, from the beginning of a signal, after how long to reach all points.
This problem is the shortest distance from the beginning to the farthest point, and the result can be obtained by Dijkstra algorithm.
In the code I used the set< pair<int, int> > structure to record the nodes to be traversed.
Pair.first is Cost,pair.second is the number of nodes.
Because set will be automatically sorted, will be in accordance with the cost from small to large platoon, the biggest advantage is that the cost of the corresponding relationship with the node can be recorded
Class Solution {public:int Networkdelaytime (vector<vector<int>>& times, int N, int start) {
start = 1;
int n = n;
int cannotreach = 99999999;
vector< vector<int> > G (N, vector<int> (N,cannotreach));
for (int i = 0; i < times.size (); i++) {g[times[i][0]-1][times[i][1]-1] = times[i][2];
}//int n = g.size ();
Vector<int> Dist (n, Cannotreach);
Vector<int> prev (n,-1);
Dist[start] = 0;
set< Pair<int, int> > S;
S.insert (Make_pair (0, start));
set< pair<int,int> >::iterator it;
int maxd = 0;
int count = 0;
while (!s.empty ()) {count++;
int mind = (*s.begin ()).
Maxd = Max (Maxd, mind);
int node = (*s.begin ()). Second;
S.erase (S.begin ()); for (int i = 0; i < n; i++) {if (mind+g[node][I] < Dist[i]) {dist[i] = Mind+g[node][i];
Prev[i] = node; for (it = S.begin (); it!= s.end (); it++) {if ((*it). Second = i) {s
. Erase (it);
Break
} s.insert (Make_pair (dist[i], i));
}} if (Count < n) return-1;
return maxd; }
};