-
Notifications
You must be signed in to change notification settings - Fork 3
/
dijkstra.cc
58 lines (56 loc) · 1.29 KB
/
dijkstra.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <vector>
#include <cstring>
#include <cstdio>
#include <queue>
#include <climits>
using namespace std;
#define pb(x) push_back(x)
#define MAXNODE 100
#define INF INT_MAX
#define ff first
#define ss second
#define sz size()
typedef pair< int, int > pii;
typedef queue <int> qi;
vector< pii > g[MAXNODE];
int d[MAXNODE];
class cmp {
public:
int operator() ( const pair<int, int>& p1,
const pair<int, int>& p2 ) {
return p1.second > p2.second;
}
};
int dijkstra(int n, int src){
int i,u,v;
priority_queue<pii,vector<pair<int,int> >,cmp > q;
for(i=0;i<n;i++)d[i]=INF;
q.push(pii(src,0));
d[src]=0;
while(!q.empty()){
u = q.top().ff;q.pop();
for(i=0;i<g[u].sz;i++)
{
v = g[u][i].first;
int vcost=d[u]+g[u][i].second;
if(vcost<d[v]){
d[v]=vcost;
q.push(pii(v,d[v]));
}
}
}
return 0;
}
int main () {
int n, e, i, u, v, w,src;
scanf("%d %d",&n,&e);
for(i = 0; i < n; i++) g[i].clear(); // forget previous info
for(i = 0; i < e; i++) {
scanf("%d %d %d",&u,&v,&w);
u--;v--;
g[u].pb(pii(v, w));
g[v].pb(pii(u, w));//if graph is undirected
}
dijkstra(n,src);
return 0;
}