Cod sursa(job #2843473)

Utilizator rapidu36Victor Manz rapidu36 Data 2 februarie 2022 15:36:19
Problema Algoritmul lui Dijkstra Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.21 kb
#include <stdio.h>
#include <stdlib.h>
#define N 50001
#define M 250001
#define INF 1000000001

typedef struct
{
    int vf, c, urm;
} element;

element v[M];
int lst[N], d[N], h[N], poz[N], n, m, nr, nh;
FILE *in, *out;

void adauga_succesor(int x, int y, int c)
{
    ++nr;
    v[nr].vf = y;
    v[nr].c = c;
    v[nr].urm = lst[x];
    lst[x] = nr;
}

void schimb(int p1, int p2)
{
    int aux = h[p1];
    h[p1] = h[p2];
    h[p2] = aux;
    poz[h[p1]] = p1;
    poz[h[p2]] = p2;
}

void urca(int p)
{
    while (p > 1 && d[h[p]] < d[h[p/2]])
    {
        schimb(p, p/2);
        p /= 2;
    }
}

void coboara(int p)
{
    int fs = 2*p, fd = 2*p + 1, bun = p;
    if (fs <= nh && d[h[fs]] < d[h[bun]])
    {
        bun = fs;
    }
    if (fd <= nh && d[h[fd]] < d[h[bun]])
    {
        bun = fd;
    }
    if (bun != p)
    {
        schimb(bun, p);
        coboara(bun);
    }
}

void sterge(int p)
{
    if (p == nh)
    {
        nh--;
    }
    else
    {
        h[p] = h[nh--];
        poz[h[p]] = p;
        urca(p);
        coboara(p);
    }
}

void dijkstra(int x0)
{
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;

    }
    d[x0] = 0;
    h[++nh] = x0;
    poz[x0] = nh;
    while (nh > 0)
    {
        int x = h[1];
        sterge(1);
        for (int p = lst[x]; p != 0; p = v[p].urm)
        {
            int y = v[p].vf;
            int c = v[p].c;
            if (d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                if (poz[y] == 0)
                {
                    h[++nh] = y;
                    poz[y] = nh;
                }
                urca(poz[y]);
            }
        }
    }
}

int main()
{
    in = fopen("dijkstra.in", "r");
    out = fopen("dijkstra.out", "w");
    fscanf(in, "%d%d", &n, &m);
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        fscanf(in, "%d%d%d", &x, &y, &c);
        adauga_succesor(x, y, c);
    }
    dijkstra(1);
    for (int i = 2; i <= n; i++)
    {
        if (d[i] == INF)
        {
            d[i] = 0;
        }
        fprintf(out, "%d ", d[i]);
    }
    fclose(in);
    fclose(out);
    return 0;
}