Cod sursa(job #1702117)

Utilizator panteapaulPantea Paul panteapaul Data 14 mai 2016 15:44:21
Problema Sate Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.56 kb
#include <iostream>
#include <fstream>
#include <list>
#include <unordered_map>

using namespace std;

typedef pair<short,int> paer;

struct nod {
    paer p;
    nod *next;
};

int main()
{
    FILE *in = fopen("sate.in", "r");
    FILE *out = fopen("sate.out", "w");

    unordered_map<short,nod*> vecini;
    unordered_map<short,int> distante;

    short n, x, y, a, b;
    int d, i, m;
    fscanf(in, "%hd%d%hd%hd", &n, &m, &x, &y);

    for (i=0; i<m; i++) {
        fscanf(in, "%hd%hd%d", &a, &b, &d);

        nod *l = new nod;
        l->p = paer(b, d);
        l->next = vecini[a];
        vecini[a] = l;

        l = new nod;
        l->p = paer(a, d);
        l->next = vecini[b];
        vecini[b] = l;
    }

    list<short> bf;
    short sat = x;
    bf.push_back(sat);

    while (!bf.empty()) {
        sat = bf.front();
        d = distante[sat];
        bf.pop_front();

        list<paer>::iterator it;

        nod *l = vecini[sat];
        while (l) {
            paer p = l->p;

            if (!distante[p.first]) {
                if (sat > p.first) {
                    distante[p.first] = d - p.second;
                }
                else {
                    distante[p.first] = d + p.second;
                }

                if (p.first == y) {
                    goto sol;
                }
                bf.push_back(p.first);
            }

            l = l->next;
        }
    }

    sol:

    fprintf(out, "%d", distante[y]);

    fclose(in);
    fclose(out);
    return 0;
}