Stanford 算法入门 week 5 dijkstra 及其堆优化 stringstream

来源:互联网 发布:js true false 判断 编辑:程序博客网 时间:2024/06/05 19:55


--------------------------------------------------------

Question 1

In this programming problem you'll code up Dijkstra's shortest-path algorithm. 
Download the text file here. (Right click and save link as). 
The file contains an adjacency list representation of an undirected weighted graph with 200 vertices labeled 1 to 200. Each row consists of the node tuples that are adjacent to that particular vertex along with the length of that edge. For example, the 6th row has 6 as the first entry indicating that this row corresponds to the vertex labeled 6. The next entry of this row "141,8200" indicates that there is an edge between vertex 6 and vertex 141 that has length 8200. The rest of the pairs of this row indicate the other vertices adjacent to vertex 6 and the lengths of the corresponding edges.

Your task is to run Dijkstra's shortest-path algorithm on this graph, using 1 (the first vertex) as the source vertex, and to compute the shortest-path distances between 1 and every other vertex of the graph. If there is no path between a vertex v and vertex 1, we'll define the shortest-path distance between 1 and v to be 1000000. 

You should report the shortest-path distances to the following ten vertices, in order: 7,37,59,82,99,115,133,165,188,197. You should encode the distances as a comma-separated string of integers. So if you find that all ten of these vertices except 115 are at distance 1000 away from vertex 1 and 115 is 2000 distance away, then your answer should be 1000,1000,1000,1000,1000,2000,1000,1000,1000,1000. Remember the order of reporting DOES MATTER, and the string should be in the same order in which the above ten vertices are given. Please type your answer in the space provided.

IMPLEMENTATION NOTES: This graph is small enough that the straightforward O(mn) time implementation of Dijkstra's algorithm should work fine. OPTIONAL: For those of you seeking an additional challenge, try implementing the heap-based version. Note this requires a heap that supports deletions, and you'll probably need to maintain some kind of mapping between vertices and their positions in the heap.
-------------------------------------------------------

要用dijkstra + heap 堆优化

参考这位牛人的博客:http://blog.csdn.net/biran007/article/details/4087866  && http://blog.csdn.net/biran007/article/details/4088132
这两篇讲的很透彻。他分别列出了 Heap + Dijsktra, STL的priority_queue + Dijsktra,naive Dijsktra的代码

我的第一版代码没有使用heap,读取data时使用stringstream可以借鉴下

#include <iostream>#include <fstream>#include <string>#include <vector>#include <sstream>#define MAX 200#define MAX_LEN 1000000using namespace std;struct node {int number;bool known;int previous;int dist;};int matrix[MAX + 1][MAX + 1];node graph[MAX + 1];vector<int> X;int ten[10] = { 7,37,59,82,99,115,133,165,188,197 };void readData(char * path) {ifstream fin(path);if(fin.fail()) {cout<<"File Open Error!"<<endl;return;}int from, to, len;string line;while(!fin.eof()) {getline(fin, line);stringstream st(line);st>>from;while(st>>to) {char c;st>>c;if(c != ',') {cout<<"File Format Error!"<<endl;return;}//以上判断逗号的语句可以用一句代替//st.ignore(); //括号内可写参数代表skip element的个数,默认为1st>>len;matrix[from][to] = len;}}}void initGraph() {for(int i = 0; i < MAX + 1; i++) {graph[i].known = false;graph[i].number = i;graph[i].previous = 0;graph[i].dist = MAX_LEN;}}void dijkstra(int s) {graph[s].dist = 0;int curr, next, shortest;while(X.size() < MAX) {shortest = MAX_LEN;//find vertex in Q with smallest distance in maxtrix[] for(int i = 1; i <= MAX; i++) {if( !graph[i].known && graph[i].dist < shortest) {shortest = graph[i].dist;next = i;}}curr = next;//若最短的边不可达,退出循环if(shortest == MAX_LEN) break;//curr为目前最近vertex,将其标注known且存入XX.push_back(curr);graph[curr].known = true;//对curr的所有邻点进行处理for(int j = 1; j <= MAX; j++) {if(matrix[curr][j] > 0 && graph[curr].dist + matrix[curr][j] < graph[j].dist) {graph[j].dist = graph[curr].dist + matrix[curr][j];graph[j].previous = curr;}}}}int main() {readData("dijkstraData.txt");initGraph();dijkstra(1);ofstream fout("out.txt");for(int i = 0; i < 10; i++) {fout<<graph[ ten[i] ].dist<<',';}fout.close();return 0;}

Pseudocode for Dijkstra

 1  function Dijkstra(Graph, source): 2      for each vertex v in Graph:                                // Initializations 3          dist[v] := infinity ;                                  // Unknown distance function from  4                                                                 // source to v 5          previous[v] := undefined ;                             // Previous node in optimal path 6                                                                 // from source 7       8      dist[source] := 0 ;                                        // Distance from source to source 9      Q := the set of all nodes in Graph ;                       // All nodes in the graph are10                                                                 // unoptimized - thus are in Q11      while Q is not empty:                                      // The main loop12          u := vertex in Q with smallest distance in dist[] ;    // Start node in first case13          if dist[u] = infinity:14              break ;                                            // all remaining vertices are15                                                                 // inaccessible from source16          17          remove u from Q ;18          for each neighbor v of u:                              // where v has not yet been 19                                                                 //              removed from Q.20              alt := dist[u] + dist_between(u, v) ;21              if alt < dist[v]:                                  // Relax (u,v,a)22                  dist[v] := alt ;23                  previous[v] := u ;24                  decrease-key v in Q;                           // Reorder v in the Queue25      return dist;





原创粉丝点击