Cod sursa(job #2009216)

Utilizator Horia14Horia Banciu Horia14 Data 8 august 2017 22:49:26
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include<cstdio>
#include<vector>
#define MAX_N 50000
#define oo 0x3f3f3f3f
using namespace std;

vector<pair<int, int>> G[MAX_N+1];
int dist[MAX_N+1], h[MAX_N+1], pos[MAX_N+1], n, m, k;

inline void Swap(int i, int j)
{
    int aux = h[i];
    h[i] = h[j];
    h[j] = aux;
    aux = pos[h[i]];
    pos[h[i]] = pos[h[j]];
    pos[h[j]] = aux;
}

void heapDown(int i)
{
    if(2*i > k) return;
    int l, r;
    l = dist[h[2*i]];
    if(2*i+1 <= k)
        r = dist[h[2*i+1]];
    else r = l + 1;
    if(l < r)
    {
        if(dist[h[i]] <= l) return;
        Swap(i,2*i);
        heapDown(2*i);
    }
    else
    {
        if(dist[h[i]] <= r) return;
        Swap(i,2*i+1);
        heapDown(2*i+1);
    }
}

void heapUp(int i)
{
    if(dist[h[i/2]] <= dist[h[i]]) return;
    Swap(i,i/2);
    heapUp(i/2);
}

void Dijkstra(int source)
{
    int i, Node;
    vector<pair<int, int>>::iterator it;
    for(i=1; i<=n; i++)
    {
        dist[i] = oo;
        h[i] = pos[i] = i;
    }
    k = n;
    dist[source] = 0;
    for(i=1; i<=n; i++)
    {
        Node = h[1];
        Swap(1,k);
        k--;
        heapDown(1);
        for(it = G[Node].begin(); it != G[Node].end(); it++)
            if(dist[(*it).first] > dist[Node] + (*it).second)
            {
                dist[(*it).first] = dist[Node] + (*it).second;
                heapUp(pos[(*it).first]);
            }
    }
}


int main()
{
    int i, x, y, cost;
    FILE *fin, *fout;
    fin = fopen("dijkstra.in","r");
    fout = fopen("dijkstra.out","w");
    fscanf(fin,"%d%d",&n,&m);
    for(i=1; i<=m; i++)
    {
        fscanf(fin,"%d%d%d",&x,&y,&cost);
        G[x].push_back(make_pair(y,cost));
    }
    fclose(fin);
    Dijkstra(1);
    for(i=2; i<=n; i++)
        if(dist[i] != oo)
            fprintf(fout,"%d ",dist[i]);
        else fprintf(fout,"0 ");
    fprintf(fout,"\n");
    fclose(fout);
    return 0;
}