Pagini recente » Cod sursa (job #1433637) | Cod sursa (job #1622223) | Cod sursa (job #2722336) | Cod sursa (job #2895778) | Cod sursa (job #2135797)
#include <bits/stdc++.h>
struct edge
{
int v, cost;
};
int nodes, edges, u, v, cost;
std :: vector<edge> adj[50001];
int distance[50001], visited[50001], OO = (1 << 31) - 1;
bool inQueue[50001];
struct orderByDistance
{
bool operator()(int x, int y)
{
return distance[x] > distance[y];
}
};
std :: priority_queue<int, std :: vector<int>, orderByDistance> Q;
bool Dijkstra(int source)
{
for(int i = 1; i <= nodes; i++)
{
distance[i] = OO;
}
distance[source] = 0;
Q.push(source);
inQueue[source] = true;
while(!Q.empty())
{
int u = Q.top(); Q.pop();
inQueue[u] = false;
for(edge i : adj[u])
{
int v = i.v, cost = i.cost;
if(distance[v] > distance[u] + cost)
{
if(++visited[v] == nodes)
{
return false;
}
distance[v] = distance[u] + cost;
if(!inQueue[v])
{
Q.push(v);
inQueue[v] = true;
}
}
}
}
return true;
}
# define verf ++poz == hg ? fread ( ch, 1, hg, stdin ), poz = 0 : 0
const int hg = 8192;
int poz = 0; char ch[hg];
inline void read(int &x)
{
int semn = 1;
if(ch[0] == '\0' ) fread(ch, 1, hg, stdin);
else for(; (ch[poz] < '0' || ch[poz] > '9') && ch[poz] != '-'; verf);
for(x = 0; ch[poz] >= '0' && ch[poz] <= '9' || ch[poz] == '-';
(ch[poz] == '-' ? semn = -1 : x = x * 10 + ch[poz] - '0'), verf);
x *= semn;
}
int main(){
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
read(nodes), read(edges);
for(int i = 1; i <= edges; i++)
{
read(u), read(v), read(cost);
adj[u].push_back({v, cost});
}
if(Dijkstra(1))
{
for(int i = 2; i <= nodes; i++)
{
printf("%d ", distance[i] == OO ? 0 : distance[i]);
}
}
else
{
printf("Ciclu negativ!");
}
return 0;
}