-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdjakstra.cpp
87 lines (81 loc) · 1.42 KB
/
djakstra.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int at,cost;
Node(int _at,int _cost)
{
at= _at;
cost= _cost;
}
};
bool operator<(Node A,Node B)
{
return A.cost>B.cost;
}
struct Edge
{
int v,w;
Edge(int x,int y)
{
v=x;
w=y;
}
};
vector<Edge> adj[600];
priority_queue<Node> PQ;
int dist[600];
int n;
void dijkastra(int s)
{
for(int i=1;i<=n;i++)
{
dist[i]=1000000000;
}
dist[s]=0;
PQ.push(Node(s,0));
while(!PQ.empty())
{
Node u=PQ.top();
PQ.pop();
if(u.cost!=dist[u.at])
{
continue;
}
for(int i=0;i<adj[u.at].size();i++)
{
Edge e=adj[u.at][i];
if(dist[e.v]>u.cost+e.w)
{
dist[e.v]=u.cost+e.w;
PQ.push(Node(e.v,dist[e.v]));
}
}
}
}
int main()
{
int ts,t=1,m,u,v,w,i;
cin>>ts;
for(int k=1;k<=ts;k++)
{
cin>>n>>m;
for(i=1;i<=m;i++)
{
cin>>u>>v>>w;
adj[u].push_back(Edge(v,w));
adj[v].push_back(Edge(u,w));
}
//cin>>t;
dijkastra(t);
printf("Case %d: ",k);
//puts("");
if(dist[n]==1000000000) cout<<"Impossible"<<endl;
else cout<<dist[n]<<endl;
for(i=0;i<=n;i++)
{
adj[i].clear();
}
}
return 0;
}