-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiSourceDijkstra.cpp
More file actions
98 lines (78 loc) · 1.73 KB
/
MultiSourceDijkstra.cpp
File metadata and controls
98 lines (78 loc) · 1.73 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
//AnkitCode99 here....
// The problem statement goes like.
// Each node and edge has some weight. For each node you can either
// stay at the same node of visit some other node following a certain
// path such that the total weight you choose in either of the case
// for each node is minimised.
#include<bits/stdc++.h>
#define endl "\n"
#define IOS ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr)
typedef long long int ll;
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define pb push_back
using namespace std;
const ll sz=1e5+5;
const ll szz=1e6+6;
const ll mod=1e9+7;
vector<pair<ll,ll>> ar[sz];
ll cost[sz],ans[sz];
ll n,m,w;
void MultiSourceDijkstra()
{
set<pair<ll,ll>> q;
for(ll i=1;i<=n;i++)
{
ans[i]=cost[i];
q.insert({i,cost[i]});
}
while(!q.empty())
{
ll current_node = (q.begin())->first;
ll current_cost = q.begin()->second;
q.erase(q.begin());
for(auto it:ar[current_node])
{
ll node = it.first;
ll costt = it.second;
if(ans[node] > ans[current_node]+costt)
{
q.erase({node,ans[node]});
ans[node]=ans[current_node]+costt;
q.insert({node,ans[node]});
}
}
}
}
int main()
{
cin>>n>>m;
for(ll i=0;i<m;i++)
{
ll a,b,w;
cin>>a>>b>>w;
ar[a].pb({b,2*w});
ar[b].pb({a,2*w});
}
for(ll i=1;i<=n;i++)
{
cin>>cost[i];
}
MultiSourceDijkstra();
for(ll i=1;i<=n;i++)
{
cout<<ans[i]<<" ";
}
cerr << endl <<setprecision(20)<< double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
}//Goodbye...
/*
Sample Input
3 3
1 2 1
2 3 1
1 3 1
30 10 20
12 10 12
Time Coplexity - O(|V|log(|V|))
Space Complexity - O (|V|)
where, |V| denotes the number of nodes
*/