Stanford - Algorithms: Design and Analysis, Part 1 - Week 5 Assignment: Dijkstra

本次作业要求如下:

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算法

本次作业的难度并不高,主要是我偷懒选择了naive的算法,时间复杂度是O(mn),如果用heap的话时间复杂度会是O(mlogn)。。。不过我对MOOC课程的态度就是达到课程的8成要求即可,不要花费太久的时间,如果需要学习的扎实,要么是在实体课上学习+做project,要么就是撸书。。。好吧,我就是为我的懒散找借口。。。囧。。。

本次作业,我是花费了很大的功夫在导入文件。。。这主要是文件形式有点怪。。

比如文件的一行是:2 3,1 4,2

这意味着start是2,然后与他相邻的有两个点3,4.。这两个点到2的距离分别是1,2

以下函数实现这个过程:

void store_file(string filename) {
	ifstream infile;
	infile.open(filename, ios::in);
	string line;
	while (getline(infile, line)) {
		int tmp;
		istringstream istr_l1(line);
		istr_l1 >> tmp;
		graph.insert(pair<int, vector<pairs>>(tmp, vector<pairs>()));
		unvisited.insert(tmp);
		string token_l1;
		while (istr_l1 >> token_l1) {
			istringstream istr_l2(token_l1);
			int end;
			int dist;
			char comma;
			istr_l2 >> end >> comma >> dist;
			pairs tmp_1 = {tmp, end, dist};
			graph[tmp].push_back(tmp_1);
		}
	}
	infile.close();
}
然后就是算法了,算法的过程和伪代码可以看下图:


这个算法比较通俗的讲就是:X是已访问点的集合,V-X是未访问点的集合,寻着在X里的一点u, V-X的一点v,此时u到原点的距离已知,要找到原点最近的v,v的计算是u到原点的距离加上u-v长度。。。找到后,把v添加到X集合,并从X-V中删除

算法的实现如下:

map<int, int> dijkstra(int s) {
	map<int, int> res;
	res.insert(pair<int, int>(s, 0));
	visited.insert(s);
	unvisited.erase(s);
	while (unvisited.size() > 0) {
		int min_len = 1000000;
		int v_star = 0;
		int w_star = 0;
		for (set<int>::iterator it = visited.begin(); it != visited.end(); ++it) {
			for(int i = 0; i < graph[*it].size(); ++i) {
				if (unvisited.find(graph[*it][i].end) != unvisited.end()) {
					int len = res[*it] + graph[*it][i].dist;
					if (min_len > len) {
						min_len = len;
						v_star = *it;
						w_star = graph[*it][i].end;
					}
				}
			}
		}
		unvisited.erase(w_star);
		visited.insert(w_star);
		res.insert(pair<int, int>(w_star, min_len));
	}
	return res;
}
然后就是完整的代码了:

# include <iostream>
# include <fstream>
# include <sstream>
# include <map>
# include <vector>
# include <string>
# include <set>

using namespace std;

const int MAX = 1000000;

struct pairs {
	int start;
	int end;
	int dist;
};

void store_file(string);
void print_graph();
map<int, int> dijkstra(int);

map<int, vector<pairs>> graph;
set<int> visited;
set<int> unvisited;

int main(int argc, char** argv) {

	store_file("dijkstraData.txt");

//	print_graph();

	map<int, int> res = dijkstra(1);

	for (map<int, int>::iterator it = res.begin(); it != res.end(); ++it) {
		if (it->first == 7 or it->first == 37 or it->first == 59 or it->first == 82 or it->first == 99 or
			it->first == 115 or it->first == 133 or it->first == 165 or it->first == 188)
			cout << it->second << ",";
		if (it->first == 197)
			cout << it->second << endl;
	}

	return 0;
}

void store_file(string filename) {
	ifstream infile;
	infile.open(filename, ios::in);
	string line;
	while (getline(infile, line)) {
		int tmp;
		istringstream istr_l1(line);
		istr_l1 >> tmp;
		graph.insert(pair<int, vector<pairs>>(tmp, vector<pairs>()));
		unvisited.insert(tmp);
		string token_l1;
		while (istr_l1 >> token_l1) {
			istringstream istr_l2(token_l1);
			int end;
			int dist;
			char comma;
			istr_l2 >> end >> comma >> dist;
			pairs tmp_1 = {tmp, end, dist};
			graph[tmp].push_back(tmp_1);
		}
	}
	infile.close();
}

void print_graph() {
	for (map<int, vector<pairs>>::iterator it = graph.begin(); it != graph.end(); ++it) {
		cout << it->first << ": ";
		for (int i = 0; i < it->second.size(); ++i) {
			cout << "(" << it->second[i].start << ", " << it->second[i].end << ", "
			<< it->second[i].dist << ") ";
		}
		cout << endl;
	}
}

map<int, int> dijkstra(int s) {
	map<int, int> res;
	res.insert(pair<int, int>(s, 0));
	visited.insert(s);
	unvisited.erase(s);
	while (unvisited.size() > 0) {
		int min_len = 1000000;
		int v_star = 0;
		int w_star = 0;
		for (set<int>::iterator it = visited.begin(); it != visited.end(); ++it) {
			for(int i = 0; i < graph[*it].size(); ++i) {
				if (unvisited.find(graph[*it][i].end) != unvisited.end()) {
					int len = res[*it] + graph[*it][i].dist;
					if (min_len > len) {
						min_len = len;
						v_star = *it;
						w_star = graph[*it][i].end;
					}
				}
			}
		}
		unvisited.erase(w_star);
		visited.insert(w_star);
		res.insert(pair<int, int>(w_star, min_len));
	}
	return res;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值