Pagini recente » Cod sursa (job #496369) | Cod sursa (job #1445427) | Cod sursa (job #1408759) | Cod sursa (job #2547216) | Cod sursa (job #807123)
Cod sursa(job #807123)
#include <fstream>
#include <vector>
#include <map>
#define INFINITE ((unsigned int)0xFFFF0000)
class Cost
{
private:
unsigned int cost;
public:
Cost() : cost(INFINITE)
{
}
Cost(unsigned int _cost) : cost(_cost)
{
}
operator unsigned int & ()
{
return cost;
}
};
template<typename T>
class Line
{
private:
typedef std::map<unsigned int, T> Nodes;
private:
T defNode;
Nodes nodes;
public:
Line()
{
}
void addNode(unsigned int _uIndex, const T &_node)
{
nodes[_uIndex] = _node;
}
const T & operator [](unsigned int _uIndex) const
{
typename Nodes::const_iterator itNode;
itNode = nodes.find(_uIndex);
if (nodes.end() != itNode)
return itNode->second;
else
return defNode;
}
T & operator [](unsigned int _uIndex)
{
typename Nodes::iterator itNode;
itNode = nodes.find(_uIndex);
if (nodes.end() != itNode)
return itNode->second;
else
return defNode;
}
};
template<typename T>
class Matrix
{
private:
typedef std::vector<Line<T> > Lines;
private:
Lines lines;
public:
Matrix(unsigned int _N)
{
while(_N)
{
lines.push_back(Line<T>());
--_N;
}
}
const Line<T> & operator [](unsigned int _uIndex) const
{
return lines[_uIndex - 1];
}
Line<T> & operator [](unsigned int _uIndex)
{
return lines[_uIndex - 1];
}
};
class Graf : public Matrix<Cost>
{
private:
typedef std::vector<bool> Visited;
private:
unsigned int N;
//Visited visited;
public:
Graf(int _N) : Matrix<Cost>(_N), N(_N)
{
/*for (unsigned int uIndex = 1; uIndex <= N; ++ uIndex)
visited.push_back(false);*/
}
void dijkstra(unsigned int _source, unsigned int _x, unsigned int _c)
{
//visited[_x - 1] = true;
for (unsigned int uIndex = 1; uIndex <= N; ++ uIndex)
{
if (uIndex != _x)
{
Cost &sourceCost = (*this)[_source][uIndex];
Cost &localCost = (*this)[_x][uIndex];
if (_c + localCost <= sourceCost && localCost != INFINITE)
{
(unsigned int&)sourceCost = _c + localCost;
this->dijkstra(_source, uIndex, _c + localCost);
}
}
}
}
unsigned int getMinLength(unsigned int _x, unsigned int _y)
{
this->dijkstra(_x, _x, 0);
return (*this)[_x][_y];
}
};
int main()
{
unsigned int x, y, c;
unsigned int N, M;
std::ifstream fin("dijkstra.in");
std::ofstream fout("dijkstra.out");
fin>>N>>M;
Graf graf(N);
for (unsigned int uIndex = 0; uIndex < M; ++ uIndex)
{
fin>>x>>y>>c;
graf[x].addNode(y, Cost(c));
}
for (unsigned int uIndex = 2; uIndex < N; ++ uIndex)
fout<<graf.getMinLength(1, uIndex)<<" ";
fout<<graf.getMinLength(1, N);
fin.close();
fout.close();
return 0;
}