Pagini recente » Cod sursa (job #2684952) | Cod sursa (job #340140) | Monitorul de evaluare | Monitorul de evaluare | Cod sursa (job #1341431)
/* Bellman-ford implementation */
#include <fstream>
#include <vector>
#define pb push_back
#define VMAX 1000
#define infinite 100000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n,m,s;
struct edge{
int w;
int to;
edge *next;
};
edge* G[VMAX];
int dist[VMAX];
int pred[VMAX];
void add(struct edge **l, int n, int w)
{
edge *p = new edge;
p->to=n;
p->w=w;
p->next = *l;
*l=p;
fout<<"add "<<n<<"\n";
}
void bellman()
{
// initializam graph-ul
for(int i=1; i<=n; i++)
dist[i]=infinite;
dist[s]=0;
// relaxam de |u-1| ori graph-ul
for(int u=1; u<=n-1; u++)
for(edge *p=G[u]; p; p=p->next){
if(dist[u] + p->w < dist[p->to])
dist[p->to] = dist[u] + p->w, pred[p->to]=u;
fout<<p->to<<" - to \n";
}
// verificam ciclurile negative
for(int u=1; u<=n-1; u++)
for(edge *p=G[u]; p; p=p->next)
if(dist[u] + p->w < dist[p->to])
fout<<"Ciclu negativ!";
}
void read()
{
fin>>n>>m>>s;
for(int i=1; i<=m; ++i)
{
int a,b,c;
fin>>a>>b>>c;
add(&G[a], b, c);
}
}
int main()
{
read();
bellman();
for(int i=2; i<=n; ++i)
fout<<dist[i]<<" ";
return 0;
}