Cod sursa(job #2163831)

Utilizator bogdan10bosBogdan Sitaru bogdan10bos Data 12 martie 2018 20:07:12
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>

using namespace std;

#define FILE_IO

typedef pair<int, int> pii;

class dEsopoPape
{
public:
    int N;
    int d[50005], st[50005];
    vector<pii> edg[50005];

    void addEdge(int x, int y, int z)
    {
        edg[x].push_back({y, z});
        //edg[y].push_back({x, z});
    }

    void solve(int root)
    {
        for(int i = 1; i <= N; i++) d[i] = 1 << 30;
        d[root] = 0;

        deque<int> dq;
        st[root] = 1;
        dq.push_front(root);

        while(!dq.empty())
        {
            int nod = dq.front();
            dq.pop_front();
            st[nod] = 0;

            for(auto nxt: edg[nod])
                if(d[nxt.first] > d[nod] + nxt.second)
                {
                    d[nxt.first] = d[nod] + nxt.second;
                    if(st[nxt.first] == 0)
                    {
                        st[nxt.first] = 1;
                        dq.push_back(nxt.first);
                    }
                    else if(st[nxt.first] == 2)
                    {
                        st[nxt.first] = 1;
                        dq.push_front(nxt.first);
                    }
                }
        }

        for(int i = 1; i <= N; i++)
            if(i != root)
                printf("%d ", (d[i] == (1 << 30)) ? 0 : d[i] );
    }
}pape;

int main()
{
    #ifdef FILE_IO
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    #endif

    int N, M;
    scanf("%d%d", &N, &M);
    pape.N = N;
    for(int i = 1; i <= M; i++)
    {
        int x, y, z;
        scanf("%d%d%d", &x, &y, &z);
        pape.addEdge(x, y, z);
    }
    pape.solve(1);

    return 0;
}