Pagini recente » Cod sursa (job #2861646) | Cod sursa (job #2493170) | Cod sursa (job #2036050) | Cod sursa (job #1818285) | Cod sursa (job #2296692)
#include <bits/stdc++.h>
using namespace std;
class Node
{
// variables
public:
int node;
int cost;
private:
// functions
public:
void initialize(int n, int c)
{
node = n;
cost = c;
}
Node()
{}
Node(int n, int c)
{
initialize(n, c);
}
~Node()
{}
private:
};
class comp
{
public:
bool operator()(Node &a, Node &b)
{
return a.cost > b.cost;
}
};
vector <int> dijkstra(int start, vector <vector <Node>> &path)
{
vector <int> dist(path.size(), numeric_limits<int>::max());
priority_queue <Node, vector <Node>, comp> q;
vector <bool> viz(path.size(), false);
dist[start] = 0;
Node current, vec;
q.push(Node(start, 0));
while(!q.empty())
{
current = q.top();
q.pop();
if(!viz[current.node])
{
for(unsigned i = 0; i < path[current.node].size(); i++)
{
vec = path[current.node][i];
if(!viz[vec.node])
{
dist[vec.node] = min(dist[current.node] + vec.cost, dist[vec.node]);
q.push(Node(vec.node, dist[vec.node]));
}
}
viz[current.node] = true;
}
}
return dist;
}
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int main()
{
int n, m;
fin>>n>>m;
vector < vector <Node>> path(n + 1);
int x, y, c;
for(; m; m--)
{
fin>>x>>y>>c;
path[x].push_back(Node(y, c));
}
vector <int> ans = dijkstra(1, path);
for(int i = 2; i <= n; i++)
if(ans[i] == numeric_limits<int>::max())
fout<<0<<' ';
else
fout<<ans[i]<<' ';
fout<<'\n';
return 0;
}