Cod sursa(job #2896665)

Utilizator MagnvsDaniel Constantin Anghel Magnvs Data 30 aprilie 2022 11:00:09
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <fstream>
#include <vector>

struct str{
    int x, y;
    str( int xnew, int ynew ) {
        x = xnew;
        y = ynew;
    }
    bool operator <( str other ) {
        return y < other.y;
    }
    bool operator >( str other ) {
        return y > other.y;
    }
};

std::vector < std::vector < str > > g;
std::vector < int > d;

template <class node>
class heap {
private:
    std::vector <node> h;

public:
    bool empty( );
    node top( );
    void insert( node x );
    void erase( );
};

template <class node>
bool heap<node>::empty( ) {
    return h.empty();
}

template <class node>
node heap<node>::top( ) {
    return h.front();
}

template <class node>
void heap<node>::insert( node x ) {
    h.push_back(x);
    int p = h.size();
    while ( p > 1 && h[p-1] < h[p/2-1] ) {
        std::swap(h[p-1], h[p/2-1]);
        p /= 2;
    }
}

template <class node>
void heap<node>::erase( ) {
    std::swap(h.front(), h.back());
    h.pop_back();
    int n = h.size(), p = 1;
    while ( ( p*2 <= n && h[p-1] > h[p*2-1] ) ||
        ( p*2+1 <= n && h[p-1] > h[p*2] ) ) {

        if ( p*2+1 <= n && h[p*2] < h[p*2-1] ) {
            std::swap(h[p-1], h[p*2]);
            p = p*2+1;
        } else {
            std::swap(h[p-1], h[p*2-1]);
            p = p*2;
        }
    }
}

heap<str> h;

int main( ) {
    std::ifstream fin("dijkstra.in");
    int n, m;
    fin >> n >> m;
    g.resize(n);
    for ( int i = 0; i < m; ++ i ) {
        int x, y, z;
        fin >> x >> y >> z;
        g[x-1].push_back(str(y-1, z));
    }
    fin.close();

    d.resize(n, -1);
    d[0] = 0;
    h.insert(str(0, 0));
    while ( h.empty() == 0 ) {
        int x = h.top().x;
        int y = h.top().y;
        h.erase();
        if ( d[x] == y ) {
            for ( int i = 0; i < int(g[x].size()); ++ i ) {
                int xn = g[x][i].x;
                int yn = g[x][i].y;
                if ( d[xn] == -1 || d[xn] > d[x]+yn ) {
                    d[xn] = d[x]+yn;
                    h.insert(str(xn, d[xn]));
                }
            }
        }
    }

    std::ofstream fout("dijkstra.out");
    for ( int i = 1; i < n; ++ i ) {
        if ( d[i] != -1 ) {
            fout << d[i] << " ";
        } else {
            fout << "0 ";
        }
    }
    fout << "\n";
    fout.close();
    return 0;
}