Pagini recente » Cod sursa (job #2569441) | Cod sursa (job #1218313) | Cod sursa (job #1492680) | Cod sursa (job #2939622) | Cod sursa (job #2547070)
#include <bits/stdc++.h>
#define pii pair<int,int>
#define make_pii(a,b) make_pair(a,b)
#define INF -1
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n,m;
const int lmt = 5e4+1;
int dist[lmt]={INF};
bool viz[lmt];
vector<pii> aList[lmt];
priority_queue<pii, vector<pii>, greater<pii> > pq;
void citire()
{
fin>>n>>m;
for(int i=1;i<=m;++i)
{
int x,y,p;
fin>>x>>y>>p;
pii a = make_pii(y,p);
aList[x].push_back(a);
}
//first ii nodul, second ii costul
}
void dijkstra(int nod)
{
//first ii nodul curent si second ii distanta de la el la nod
pii strtNod = make_pii(nod,0);
dist[nod] = 0;
viz[strtNod.first] = 1;
pq.push(strtNod);
while(!pq.empty())
{
pii crnt = pq.top();
pq.pop();
viz[crnt.first]=1;
if(dist[crnt.first] < crnt.second)
continue;
vector<pii>::iterator i;
for(i = aList[crnt.first].begin();i!=aList[crnt.first].end();++i)
{
pii nd = *i;
if(viz[nd.first])continue;
int newDistance = dist[crnt.first] + nd.second;
if(dist[nd.first] == INF)
{
dist[nd.first] = newDistance;
pii toAdd = make_pii(nd.first,dist[nd.first]);
pq.push(toAdd);
}
else if(dist[nd.first]>newDistance)
{
dist[nd.first] = newDistance;
pii toAdd = make_pii(nd.first,dist[nd.first]);
pq.push(toAdd);
}
}
}
}
int main()
{
citire();
for(int i=1;i<=n;++i)
dist[i]=INF;
dijkstra(1);
for(int i=2;i<=n;++i)
fout<<(dist[i] == INF ? 0 : dist[i])<<' ';
return 0;
}