# How to solve this problem using Dijkstra?

Problem
I’ve solved this using Prim’s algo. I think it can also be done using Dijkstra but i’m not able to optimize my code to pass cases like:

4 3
0 1 0 1
1 2 2
3 4 2
1 3 1
Output : 3

Please help. Thanks.

share your dijkistra’s code . . . .

Code
``````constexpr int N = 100100;
priority_queue<pair<ll,int>,vector<pair<ll,int>>,greater<pair<ll,int>>> q;
vector<pii> adj[N];
bitset<1> vis[N];
int assigned[N];
ll dist[N];
void djk(){
while(!q.empty()){
auto x = q.top();
q.pop();
if(vis[x.second] == 0){
vis[x.second] = 1;
for(auto nxt : adj[x.second]){
if(dist[x.second] + nxt.second <= dist[nxt.first]){

dist[nxt.first] = dist[x.second] + nxt.second; // update min cost from any milkman

assigned[nxt.first] = min(assigned[nxt.first], nxt.second); // select best edge

q.push({dist[nxt.first], nxt.first});
}
}
}
}
}
void solve(){
q = priority_queue<pair<ll,int>,vector<pair<ll,int>>,greater<pair<ll,int>>> ();
for(int i = 1; i < N; ++i) adj[i].clear(), dist[i] = LLONG_MAX, vis[i] = 0, assigned[i] = INT_MAX;
int n,m;
cin >> n >> m;
int good[n+1];
for(int i = 1; i <= n; ++i){
cin >> good[i];
if(good[i]){
q.push({0,i});
dist[i] = 0;
assigned[i] = 0;
}
}
rep(i,0,m){
int u,v,w;
cin >> u >> v >> w;
adj[u].pb({v,w});
adj[v].pb({u,w});
}
ll ans = 0;
djk();
for(int i = 1; i <= n; ++i){

if(assigned[i] == INT_MAX){
cout << "impossible" << '\n';
return;
}
else ans += assigned[i];
}
cout << ans << '\n';

}
``````

This would give Output : 4 for the mentioned TC.