Pagini recente » Cod sursa (job #227436) | Cod sursa (job #2330948) | Cod sursa (job #1098197) | Cod sursa (job #1444349) | Cod sursa (job #2854661)
#include <bits/stdc++.h>
#define Dmax 50005
#define inf 0x3F3F3F3F
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int n,m,D[Dmax];
vector<pair<int,int> >G[Dmax];
struct Compare{
bool operator()(pair<int,int>a, pair<int,int>b)
{
return (D[a.first] < D[b.first]);
}
};
priority_queue<pair<int,int>, vector<pair<int,int> >, Compare> Q;
void Dijkstra(int start)
{
for(int i = 1; i <= n; i++)
D[i] = inf;
D[start] = 0;
Q.push({start,0});
while(!Q.empty())
{
int nod = Q.top().first;
int cost = Q.top().second;
Q.pop();
if(cost > D[nod])
continue;
for(vector<pair<int,int > >::iterator it = G[nod].begin(); it < G[nod].end(); it++)
{
if(D[it->first] > D[nod] + it->second)
{
D[it->first] = D[nod] + it->second;
Q.push({it->first,it->second});
}
}
}
}
int main()
{
f>>n>>m;
for(int i = 1; i <= m; i++)
{
int x,y,z;
f>>x>>y>>z;
G[x].push_back({y,z});
}
Dijkstra(1);
for(int i = 2; i <= n; i++)
if(D[i]==inf)
g<<"0 ";
else
g<<D[i]<<" ";
return 0;
}