Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define INF 1e18+7
- #define M 100100
- #define ll long long
- vector<ll>edge[M],cost[M];
- ll parent[M];
- ll s,desti;
- bool visited[M];
- struct data
- {
- ll city,dist;
- bool operator<(const data& p) const
- {
- return dist>p.dist;
- }
- };
- ll dijkstra(ll source,ll destination)
- {
- ll d[M];
- for(int i=0;i<M;i++)
- {
- d[i]=INF;
- parent[i]=-1;
- }
- priority_queue<data>q;
- data u,v;
- u.city=source;
- u.dist=0;
- q.push(u);
- d[source]=0;
- while(!q.empty())
- {
- u=q.top();
- q.pop();
- ll ucost=d[u.city];
- //cout<<u.city<<endl;
- for(ll i=0;i<edge[u.city].size();i++)
- {
- v.city=edge[u.city][i];
- v.dist=cost[u.city][i]+ucost;
- //relaxing
- if(d[v.city]>v.dist)
- {
- d[v.city]=v.dist;
- parent[v.city]=u.city;
- //cout<<v.city<<endl;
- q.push(v);
- }
- }
- }
- return d[destination];
- }
- void printpath(int x)
- {
- if(x==1)
- {
- cout<<1<<" ";
- return;
- }
- printpath(parent[x]);
- cout<<x<<" ";
- }
- int main()
- {
- ll n,m;
- cin>>n>>m;
- data get;
- while(m--)
- {
- ll a,b,w;
- cin>>a>>b>>w;
- edge[a].push_back(b);
- edge[b].push_back(a);
- cost[a].push_back(w);
- cost[b].push_back(w);
- }
- ll prime= dijkstra(1,n);
- if(prime==INF)
- {
- cout<<-1<<endl;
- }
- else
- {
- printpath(n);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment