2013-12-15 2 views
-1

Я работаю над проектом, чтобы найти кратчайший путь в графе, и я должен быть в состоянии указать начальную и конечную вершины. У меня больше всего сделано с помощью Boost, но у меня остался один вопрос. Как указать начальную вершину? Вот мой код. Если бы вы могли указать мне в правильном направлении, я был бы очень благодарен. Линия, о которой идет речь, относится ко всем **, расположенным внизу.Как читать в начальной вершине?

#include <iostream> 
#include <fstream> 
#include <map> 
#include <vector> 
#include <string> 
#include <boost/graph/adjacency_list.hpp> 
#include <boost/graph/visitors.hpp> 
#include <boost/graph/breadth_first_search.hpp> 
#include <boost/graph/dijkstra_shortest_paths.hpp> 
#include <boost/graph/metis.hpp> 

using namespace std; 

typedef boost::adjacency_list_traits< 
boost::vecS, boost::vecS, boost::undirectedS, boost::listS> GraphTraits; 
typedef GraphTraits::vertex_descriptor Vertex; 
struct VertexProperty { 
string name; 
Vertex predecessor; 
double distance; 
boost::default_color_type color; 
VertexProperty(const string& aName = "") : name(aName) { }; 
}; 
struct EdgeProperty { 
double weight; 
EdgeProperty(double aWeight = 0.0) : weight(aWeight) { }; 
}; 
struct do_nothing_dijkstra_visitor { 
template <typename Vertex, typename Graph> 
void initialize_vertex(Vertex u, const Graph& g) const { }; 
template <typename Vertex, typename Graph> 
void examine_vertex(Vertex u, const Graph& g) const { }; 
template <typename Edge, typename Graph> 
void examine_edge(Edge e, const Graph& g) const { }; 
template <typename Vertex, typename Graph> 
void discover_vertex(Vertex u, const Graph& g) const { }; 
template <typename Edge, typename Graph> 
void edge_relaxed(Edge e, const Graph& g) const { }; 
template <typename Edge, typename Graph> 
void edge_not_relaxed(Edge e, const Graph& g) const { }; 
template <typename Vertex, typename Graph> 
void finish_vertex(Vertex u, const Graph& g) const { }; 
}; 
int main() { 
string tempName1; 
string tempName2; 
string tempString; 
string data2; 
double weight; 
cout << "please enter the data file name: "; 
char strFileName[256]; 
cin >> strFileName; 
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,    VertexProperty, EdgeProperty> Graph; 
Graph g; 
// preparing the data 
ifstream fin; 
fin.open(strFileName); 
if (!fin) { 
    cerr << "Can't open data file, leaving...\n"; 
    return EXIT_FAILURE; 
} 
else{ 
    cout << "file loaded." << endl << endl; 
} 
std::map<std::string, Vertex> name2v; 
std::getline(fin, tempString); //Vertices: 
std::getline(fin, tempString); //Location1, Location2, ... 
std::stringstream tempSS(tempString); 
while (std::getline(tempSS, tempName1, ',')){ 
    name2v[tempName1] = add_vertex(VertexProperty(tempName1), g); 
} 
std::getline(fin, tempString); //Edges: 
while (std::getline(fin, tempString)){ // (Location1, Location2, 6) 
    //remove parentheses 
    tempString.erase(tempString.begin(), tempString.begin() + 
tempString.find('(') + 1); 
    tempString.erase(tempString.begin() + tempString.find(')'), 
tempString.end()); 
    std::stringstream temp_ss(tempString); 
    std::getline(temp_ss, tempName1, ','); 
    std::getline(temp_ss, tempName2, ','); 
    temp_ss >> weight; 
    add_edge(name2v[tempName1], name2v[tempName2], EdgeProperty(weight), g); 
} 
char x; 
cout << endl << "How would you like to process your data file?" << endl; 
cout << "1.) shortest path" << endl; 
cout << "2.) minimum spanning tree" << endl; 
cout << "3.) Travelling Salesman" << endl << endl; 
returnQuestion: 
cout << "please enter 1,2,3 or Q to quit: "; 
cin >> x; 
switch (x){ 
case 1: //do the work for shortest path 
    cout << "please enter the node "; 
    dijkstra_shortest_paths(
     **g, start_vertex;******************* 
     get(&VertexProperty::predecessor, g), 
     get(&VertexProperty::distance, g), 
     get(&EdgeProperty::weight, g), 
     boost::identity_property_map(), // index-map 
     less<double>(), // compare 
     plus<double>(), // combine 
     numeric_limits<double>::infinity(), // infinity 
     0.0, // zero 
     do_nothing_dijkstra_visitor(), 
     get(&VertexProperty::color, g)); 
    break; 
case 2: //do the work for minimum spanning 
    break; 
case 3: //do the work for travelling salesman 
    break; 
case 'q': 
case 'Q': 
    return EXIT_SUCCESS; 
    break; 
default: 
    goto returnQuestion; 
} 
system("pause"); 
} 

ответ

0

Чтобы определить время начала и окончания вершины просто читать строки, которые обозначают те узлы и использовать вашу name2v карту, чтобы получить объекты вершин.

Несколько точек, хотя алгоритм Дейкстры (http://en.wikipedia.org/wiki/Dijkstra 's_algorithm) - это единственный источник всех алгоритмов кратчайших путей. Это означает, что он будет вычислять кратчайшие пути от начальной вершины ко всем другим вершинам.

Если у вас есть только самый короткий путь между двумя вершинами, просто используйте глубину первого поиска.

Проверьте пример программы ускорения DFS (http://www.boost.org/doc/libs/1_55_0/libs/graph/example/dfs-example.cpp). Вы можете использовать карту предшественника для считывания фактического пути.

Смежные вопросы