Question:
There are n fields (n <= 500) on the farm, and m paths (M <= 2500) can take t units of time to arrive at J from I. There are also W wormhole holes (W <= 200), which can arrive at the other J from the ground I and timeRegressingT! Note that the path is bidirectional and the wormhole is unidirectional. Now Farmer John wants to know if he can start from a certain place and return to this place so that he can return earlier than the departure time (he can meet himself ^ ).
Analysis:
The disguise of the question is removed. It can be seen that the question requires a directed graph with negative weights.Whether a loop with a negative weight exists.
This problem isBellman-FordThe problem to be solved when finding the shortest path with a negative weight directed graph.
- /*
- Pku3259 wormholes
- */
- # Include <stdio. h>
- # Include <memory. h>
- # Define CLR (a) memset (A, 0, sizeof ())
- # Define Inf (1 <28)
- # Define n 505
- # Define M 6005
- Int bellman_ford (int e [] [3], int M, int N, int d [])
- {
- Int K, V, flag, I, J;
- For (k = 0; k <n; k ++) d [k] = inf;
- // D [0] = 0;
- For (k = 0; k <n-1; k ++)
- {
- Flag = 0;
- For (V = 0; v <m; V ++ ){
- I = E [v] [0]; j = E [v] [1];
- If (d [J]> d [I] + E [v] [2]) {
- D [J] = d [I] + E [v] [2];
- Flag = 1;
- }
- }
- If (! Flag) return 1;
- }
- For (v = 0; v <m; v ++)
- If (d [e [v] [1]> d [e [v] [0] + e [v] [2])
- Return 0;
- Return 1;
- }
- Int n, m, w;
- Int e [M] [3], ne;
- Int d [N];
- Void addEdge (int I, int j, int k ){
- E [ne] [0] = I;
- E [ne] [1] = j;
- E [ne] [2] = k;
- Ne ++;
- }
- Int main ()
- {
- Int I, j, k, t, T;
- Scanf ("% d", & T );
- While (T --){
- // Input
- Ne = 0;
- Scanf ("% d", & n, & m, & w );
- For (k = 0; k <m + w; k ++ ){
- Scanf ("% d", & I, & j, & t );
- If (k <m ){
- AddEdge (I, j, t );
- AddEdge (j, I, t );
- }
- Else {
- AddEdge (I, j,-t );
- }
- }
- // Output
- If (Bellman_Ford (e, ne, n, d) puts ("NO ");
- Else puts ("YES ");
- }
- Return 0;
- }