Pagini recente » Cod sursa (job #2747277) | Cod sursa (job #3300376) | Cod sursa (job #1298917) | Cod sursa (job #751301) | Cod sursa (job #1805781)
#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();
}