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


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

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 1000000
using 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的个数,默认为1
			st>>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且存入X
		X.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 are
10                                                                 // unoptimized - thus are in Q
11      while Q is not empty:                                      // The main loop
12          u := vertex in Q with smallest distance in dist[] ;    // Start node in first case
13          if dist[u] = infinity:
14              break ;                                            // all remaining vertices are
15                                                                 // inaccessible from source
16          
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 Queue
25      return dist;





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值