Pagini recente » Cod sursa (job #867575) | Cod sursa (job #508524) | Cod sursa (job #910376) | Cod sursa (job #1023921) | Cod sursa (job #716119)
Cod sursa(job #716119)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <cstdlib>
using namespace std;
struct node
{
int at;
int cost;
};
inline node mn (const int &at, const int &cost)
{
node nod;
nod.at = at;
nod.cost = cost;
return nod;
}
int main (int argc, char const *argv[])
{
ifstream in ("sate.in");
int n, m; in >> n >> m;
int inceput, sfarsit; in >> inceput >> sfarsit;
vector< vector<int> > edges (n + 1),
costs (n + 1);
int x, y, c;
while (in >> x >> y >> c)
{
edges[x].push_back (y);
costs[x].push_back (c);
}
in.close ();
/*
cout << "From:\n";
for (int i = 1; i <= n; i++)
{
cout << i << ": ";
for (unsigned j = 0; j < edges[i].size (); j++)
cout << edges[i][j] << ' ';
cout << '\n';
}
*/
for (int i = 1; i <= n; i++)
{
if (edges[i].size () > 1)
{
//cout << "I can infer from " << i << " that:\n";
for (unsigned j = 0; j < edges[i].size (); j++)
{
for (unsigned k = j + 1; k < edges[i].size (); k++)
{
//cout << "Got " << edges[i][j] << ' ' << edges[i][k] <<
// ' ' << abs (costs[i][j] - costs[i][k]) << '\n';
edges[edges[i][j]].push_back (edges[i][k]);
costs[edges[i][j]].push_back (abs (costs[i][j] - costs[i][k]));
}
}
}
}
vector<bool> visited (n + 1);
stack<node> stiva;
stiva.push ( mn (inceput, 0) );
visited[inceput] = true;
while (!stiva.empty ())
{
node nod = stiva.top ();
stiva.pop ();
if (nod.at == sfarsit)
{
ofstream out ("sate.out");
out << nod.cost << '\n';
out.close ();
exit (0);
}
for (unsigned i = 0; i < edges[nod.at].size (); i++)
{
if (!visited[edges[nod.at][i]])
{
stiva.push ( mn (edges[nod.at][i], nod.cost + costs[nod.at][i]) );
visited[edges[nod.at][i]] = true;
}
}
}
return 0;
}