Cod sursa(job #1907218)

Utilizator savigunFeleaga Dragos-George savigun Data 6 martie 2017 18:19:42
Problema Sate Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.9 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

typedef pair<int, int> edge;

int n, m, k, d[36001], f[36001];
bool viz[36001];
vector<edge> g[36001];
const int INF = 2e7;
priority_queue< edge, vector<edge>, greater<edge> > q;

void citire();
void afisare();
void Dijkstra();


int main() {
    citire();
    Dijkstra();
    afisare();

    return 0;
}


void Dijkstra() {
    while (!q.empty()) {
        int cost, x;
        cost = q.top().first;
        x = q.top().second;
        q.pop();

        //cout << "Popped " << x << endl;

        if (viz[x]) continue;
        viz[x] = true;

        //cout << "-entering" << endl;

        for (int i = 0, y; i < g[x].size(); ++i) {
            y = g[x][i].second;
            if (viz[y]) continue;
            //cout << "--visiting " << y << endl;
            if (cost + g[x][i].first < d[y]) {
                d[y] = cost + g[x][i].first;
                f[y] = f[x];
                //cout << "---pushed better" << endl;
                q.push(make_pair(d[y], y));
            } else if (cost + g[x][i].first == d[y]) {
                f[y] = min(f[y], f[x]);
            }
        }
    }
}

void afisare() {
    ofstream out("catun.out");

    for (int i = 1; i <= n; ++i) {
        if (f[i] == i) f[i] = 0;
        out << f[i] << " ";
    }

    out.close();
}

void citire() {
    ifstream in("catun.in");

    in >> n >> m >> k;

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

    for (int i = 1, fortress; i <= k; ++i) {
        in >> fortress;
        f[fortress] = fortress;
        d[fortress] = 0;
        q.push(make_pair(0, fortress));
    }

    for (int i = 1, x, y, c; i <= m; ++i) {
        in >> x >> y >> c;
        g[x].push_back(make_pair(c, y));
        g[y].push_back(make_pair(c, x));
    }

    in.close();
}