Pagini recente » Cod sursa (job #672533) | Cod sursa (job #617515) | Cod sursa (job #2119313) | Cod sursa (job #1741486) | Cod sursa (job #1373615)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define inf (1<<30)
using namespace std;
struct nods
{
int a,c;
}aux;
int n,m,x,y,c;
vector<vector<nods> > gf;
vector<bool> used,inq;
vector<int> dist;
queue<int> q;
void bellman(int x)
{
dist[x]=0;
q.push(x);
inq.push_back(true);
while(!q.empty())
{
x=q.front();
q.pop();
used[x]=true;
inq[x]=false;
for(int i=0; i<gf[x].size();i++)
{
int y=gf[x][i].a;
int cost=gf[x][i].c;
if(!used[y])
{
if(dist[x]+cost<dist[y])
{
dist[y]=dist[x]+cost;
if (!inq[y]){
q.push(y);
inq[y]=true;
}
}
}
}
}
}
int main()
{
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
f >> n >> m;
gf.resize(n+1);
for(int i=0; i<=n; i++)
{
dist.push_back(inf);
used.push_back(false);
inq.push_back(false);
}
for(int i=1; i<=m; i++)
{
f >> x >> y >> c;
aux.a=y;
aux.c=c;
gf[x].push_back(aux);
}
bellman(1);
for(int i=2; i<=n; i++)
{
if (dist[i]!=inf) g << dist[i] << " ";
else g << "0 ";
}
f.close();
g.close();
return 0;
}