Cod sursa(job #1805781)

Utilizator AkrielAkriel Akriel Data 14 noiembrie 2016 13:27:41
Problema Sate Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.01 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define N 30005

using namespace std;

ifstream f ("sate.in");
ofstream g ("sate.out");

struct node
{
    int info;
    int cost=-1;
    node *next;
};

node *root[N], *top[N];

int totalNodes, totalEdges, totalCost,
    nodeStart, nodeStop;

int totalDistance[N];

bool visited[N];

int answer;

void nodePushBack(int origin, int destination, int value)
{
    node *aux = new node;
    aux -> info = destination;
    aux -> cost = value;
    if ( root[origin] )
    {
        top[origin] -> next = aux;
        top[origin] = aux;
    }
    else
        root[origin] = top[origin] = aux;
    top[origin] -> next = NULL;
}

void readVariables()
{
    f >> totalNodes >> totalEdges >> nodeStart >> nodeStop;
    if ( nodeStart > nodeStop )
        swap ( nodeStart, nodeStop );

    int origin, destination, value;
    for ( ; totalEdges ; totalEdges-- )
    {
        f >> origin >> destination >> value;
        nodePushBack( origin, destination, value );
        nodePushBack( destination, origin, -value );
    }
}

void breadthFirstSearch()
{
    queue < int > Queue;
    bool found = false;

    Queue.push(nodeStart);

    for ( int nodeCurrent, costCurrent; !Queue.empty(); )
    {
        nodeCurrent = Queue.front();
        costCurrent = totalDistance[nodeCurrent];

        Queue.pop();

        for ( node *it = root[nodeCurrent]; it ; it = it -> next )
        {
            if ( !visited[it->info] )
            {
                totalDistance[it->info] = it -> cost + costCurrent;
                visited[it-> info] = true;
                Queue.push(it -> info);
            }
            if ( it -> info == nodeStop )
            {
                found = true;
                answer = totalDistance[nodeStop];
            }
        }
        if ( found )
            break;
    }
    g << answer;
}

int main()
{
    readVariables();
    breadthFirstSearch();
}