Cod sursa(job #1093541)

Utilizator ionutzm05Marisca Mihai Ionut ionutzm05 Data 28 ianuarie 2014 10:41:15
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
using namespace std;
const int INFINIT=1<<30;

int c[100][100],n,m,i,j,x,y,cost;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

void initializare(int &n,int &m)
{
    f>>n>>m;
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
            if(i!=j)
                c[i][j]=INFINIT;
            else
                c[i][j]=0;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>cost;
        c[x][y]=cost;
    }
}

void dijkstra(int x0)
{
    int i, j, min, k, ok;
    int viz[n], d[n], tata[n];
    for (i = 1; i<=n; i++) {
        d[i] = c[x0][i];
        tata[i] = x0;
        viz[i] = 0;
    }
    tata[x0] = 0;
    viz[x0] = 1; ok = 1;
    while (ok) {
        min = INFINIT;
        for (i = 1; i<=n; i++)
            if (!viz[i] && min>d[i]) {
                min = d[i];
                k = i;
            }
        if (min != INFINIT) {
            viz[k] = 1;
            for (i = 1; i<=n; i++)
               if (!viz[i] && d[i]>d[k]+c[k][i]) {
                   d[i] = d[k]+c[k][i];
                   tata[i] = k;
               }
        }
        else ok = 0;
    }
    for(i=2;i<=n;i++)
        cout<<d[i]<<" ";
}

int main()
{
    initializare(n,m);
    dijkstra(1);
    return 0;
}