///Complexity: O(mlogm). n=number of edge,n=number of node.(analysis from shanto's book)
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pi pair<ll,ll>
#define pii pair<pi,ll>
struct node{
ll a,cost;
node( ll _a,ll _cost) {
a= _a;
cost= _cost;
}
} ;
bool operator< ( node A, node B) {
/// priority queue returns the greatest value.
/// So we need to write the comperator in a way.
/// So that cheapest value becomes greatest value.
return A.cost > B.cost ;
}
struct Edge{
ll v,w;
} ;
vector< Edge> adj[ 1005 ] ;
ll dist[ 1005 ] ;
bool visit[ 1005 ] ;
ll n;
ll dijkstra( ll s,ll destination) {
priority_queue< node> PQ;
for ( ll i= 1 ; i<= n; i++ ) {
dist[ i] = 1000000000 ;
visit[ i] = 0 ;
}
dist[ s] = 0 ;
PQ.push ( node( s,0 ) ) ;
while ( ! PQ.empty ( ) ) {
node u= PQ.top ( ) ;
PQ.pop ( ) ;
if ( visit[ u.a ] ) { continue ; } /// if(u.cost!=dist[u.a]){ continue; }
visit[ u.a ] = 1 ;
///priority_queue তে edge এর weight অনুযায়ী sort হয় না। বরং, node এর cost অনুযায়ী sort হয়।
///priority_queue এর সবচেয়ে ছোট cost এর node নিয়ে আগে কাজ করব। So, সেখান থেকে যেসব জায়গায় যাব, তাদের cost আমাদের current node এর cost এর থেকে বেশি/সমান হবে। So, priority_queue এর সবচেয়ে ছোট cost এর যে node টাকে নিয়ে একবার কাজ করে ফেলব, সেটাকে নিয়ে next time আর কাজ করা লাগবে না।
if ( u.a == destination) return u.cost ;
for ( Edge e : adj[ u.a ] ) {
if ( dist[ e.v ] > u.cost + e.w ) {
dist[ e.v ] = u.cost + e.w ;
PQ.push ( node( e.v ,dist[ e.v ] ) ) ;
}
}
}
return - 1 ;
}
int main( )
{
ll i,j,m,a,b,ans= 0 ,k,c;
cin >> n>> m;
Edge aa;
for ( i= 0 ; i< m; i++ ) {
cin >> a>> b>> c;
aa.v = b;
aa.w = c;
adj[ a] .push_back ( aa) ;
aa.v = a;
adj[ b] .push_back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