Topic Links:
Http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_B
Single Source shortest Path (negative Edges)
Input
An edge-weighted graph G ( V , E ) and the source r .
|V| |Ers0t0d0s1t1d1:s|E|?1t|E|?1d|E|?1
|V|Is the number of vertices and are the number of |E| edges in G . The graph vertices is named with the numbers 0, 1,..., |V|?1 respectively. Is the source of the r graph.
siand ti represent source and target vertices of i -th edge (directed) and represents the cost of the di i -th E Dge.
Output
If The graph contains a negative cycle (a cycle whose sum of edge costs is a negative value) which are reachable from the s Ource r , Print
Negative CYCLE
In a line.
Otherwise, Print
c0c1:c|V|?1
The output consists of |V| lines. Print the cost of the shortest path from the source to each r vertex 0, 1, ... in |V|?1 order. If there is no path from the source to a vertex, print "INF".
Constraints
- 1 ≤ |V| ≤1000
- 0≤ |E| ≤2000
- -10000≤ di ≤10000
- There is no parallel edges
- There is no self-loops
Sample Input 1
4 5 00 1 20 2 31 2-51 3 12 3 2
Sample Output 1
02-3-1
Sample Input 2
4 6 00 1 20 2 31 2-51 3 12 3 23 1 0
Sample Output 2
Negative CYCLE
Sample Input 3
4 5 10 1 20 2 31 2-51 3 12 3 2
Sample Output 3
Inf0-5-3
The problem of single source shortest path + negative circle, with Bellman-ford algorithm.
Note: The negative loop here comes with the condition that the source point R can reach the negative circle.
Bellman-ford algorithm + negative loop link
Code:
#include <iostream>#include<algorithm>#include<map>#include<vector>using namespaceStd;typedefLong Longll;#defineINF 2147483647structedge{int from, To,cost;}; Edge es[ .];//Storage Edgeintd[1010];//D[i] Indicates the shortest distance from point I to source pointintV,e;//number of points and edgesBOOLShortest_path (ints) {Fill (d,d+V,inf); D[s]=0; intv =0; while(true){ BOOLUpdate =false; for(inti =0; i < E; i++) {Edge e=Es[i]; if(D[e. from]! = INF && d[e.to] > d[e. from] +e.cost) {D[e.to]= D[e. from] +E.cost; Update=true; if(v = = v.1)return true; } } if(!update) Break; V++; } return false;}intMain () {intR; CIN>> V >> E >>R; for(inti =0; i < E; i++) Cin >> Es[i]. from>> es[i].to >>Es[i].cost; if(!Shortest_path (R)) { for(inti =0; i < V; i++){ if(D[i] = = INF) cout <<"INF"<<Endl; Elsecout << D[i] <<Endl; } }Else{cout<<"Negative CYCLE"<<Endl; } return 0;}
AOJ grl_1_b:shortest path-single Source Shortest path (negative Edges) (Bellman-frod algorithm for Negative loop and single source shortest path)