# Dijkstra Single Source Shortest path

Source: Internet
Author: User
Tags cmath

`1. #include <cstdio> #include <iostream> #include <algorithm> #include <queue> #include < stack> #include <climits> #include <cstring> #include <cmath> #include <map> #include <set > #define INF 100000000using namespace Std;int n,v,m;int d[1000];int vis[1000];int g[1000][1000]; int Dijkstra (int s) {fill (D,d+n,inf), memset (vis,0,sizeof (VIS));d [s] = 0;for (int i = 0;i < n-1;i++) {int TM = Inf;int Q Find the smallest for (int j = 0;j < n;j++) {if (!vis[j] && D[j] < TM) {TM = D[j];q = j;}} in the point where the shortest path has been found Representing this point has found the shortest path vis[q] = 1; for (int j = 0;j < n;j++) {if (G[q][j]) {d[j] = min (D[j],d[q] + g[q][j]);}}} for (int i = 0;i < n;i++) {printf ("%d\n", D[i]);}} int main () {while (CIN >> n >> m) {for (int i = 0;i < m;i++) {int x,y,w;cin >> x >> y >> w; G[x][y] = W; G[y][x] = w;} int s;cin >> S;dijkstra (s);} return 0;}`

2.

`#include <cstdio> #include <iostream> #include <algorithm> #include <queue> #include <stack > #include <climits> #include <cstring> #include <cmath> #include <map> #include <set># Define INF 100000000using namespace Std;int n,v,m;int d[1000];int vis[1000];int g[1000][1000];typedef pair<int,int > Pa;int Dijkstra (int s) {fill (d,d+n,inf); memset (vis,0,sizeof (VIS));p riority_queue< Pa,vector<pa> greater<pa> > Que;que.push (PA (0,s));d [s] = 0;for (int i = 0;i < n-1;i++) {int q = que.top (). Second;que.pop (); f or (int j = 0;j < n;j++) {if (G[q][j]) {d[j] = min (D[j],d[q] + g[q][j]); Que.push (PA (d[j],j));}}} for (int i = 0;i < n;i++) {printf ("%d\n", D[i]);}} int main () {while (CIN >> n >> m) {for (int i = 0;i < m;i++) {int x,y,w;cin >> x >> y >> w; G[x][y] = W; G[y][x] = w;} int s;cin >> S;dijkstra (s);} return 0;}`

Dijkstra Single Source Shortest path

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.