最短路简化版的两种解法
2017-08-09 19:00
465 查看
#include <iostream> #include <vector> #include<queue> #include <cstring> using namespace std; class Graph { private: int n; vector<int> *v;//邻接表 bool *visited;//访问标志 public: Graph(int input_n) { n = input_n; v = new vector<int> ; visited = new bool ; memset(visited, 0, sizeof(bool)*n); } ~Graph() { delete[] v; delete[] visited; } void insert(int x, int y) { v[x].push_back(y); v[y].push_back(x); } void bfs_1(int start_vertex) { queue<int> bfs_queue; vector<int> level_vertex(n);//存储每个节点的层数 int last, nextlast;//最右元素和下一层最右元素 last = start_vertex; int level = 1;//层数 bfs_queue.push(start_vertex);//入队 visited[start_vertex] = true; while (!bfs_queue.empty()){ int vertex = bfs_queue.front(); bfs_queue.pop();//访问后弹出 for (int adj_vertex : v[vertex]){ if (!visited[adj_vertex]){ visited[adj_vertex] = true; nextlast = adj_vertex;//跟踪,直到最右元素 level_vertex[adj_vertex] = level; bfs_queue.push(adj_vertex); } } if (vertex == last){//当访问到当前层中的最右元素时,表示该换行了,到下一层 last = nextlast; level++; } } for (int i = 0; i < n - 1; i++){ cout << level_vertex[i] << endl; } cout << level_vertex[n - 1]; } //第二种方法 void bfs_2(int start_vertex){ queue<int> bfs_queue; vector<int> level_vertex(n);//存储每个节点的层数 bfs_queue.push(start_vertex);//入队 visited[start_vertex] = true; while (!bfs_queue.empty()){ int vertex = bfs_queue.front(); bfs_queue.pop();//访问后弹出 for (int adj_vertex : v[vertex]){ if (!visited[adj_vertex]){ visited[adj_vertex] = true; level_vertex[adj_vertex] = level_vertex[vertex] + 1; //更新层数 bfs_queue.push(adj_vertex); } } } for (int i = 0; i < n - 1; i++){ //按照节点序号输出 cout << level_vertex[i] << endl; } cout << level_vertex[n - 1]; } }; int main() { int n, m, c;//图的顶点数,无向边的数量,广搜的起点 cin >> n >> m >> c; Graph g(n); for (int i = 0; i < m; ++i) { int x, y; cin >> x >> y;//顶点的编号为1~n; g.insert(x-1, y-1);//插入时,内部的编号为0~n-1 } g.bfs_2(c-1);//对起点进行广度搜索,以起点为第零层,不断向外扩层,最终按节点的序号输出每个节点所在的层数。 system("pause"); return 0; }
相关文章推荐
- HDU1690(最短路 两种解法 Dijkstra和Floyd)
- Leetcode139题Word Break的两种动态规划解法
- hdu 4751 Divide Groups (两种解法 1.bfs 2.dfs)
- POJ 1515 Street Directions --一道连通题的双连通和强连通两种解法
- UVA - 10004 Bicoloring (dfs和bfs两种解法)
- 计算字符串的相似度-两种解法
- 最短路简化版(邻接矩阵和邻接表)
- leetcode 315. Count of Smaller Numbers After Self 两种思路(欢迎探讨更优解法)
- hdu 1596 find the safest road(最短路求最大值的题目,有两种稍微不同的处理方式)
- 多重背包问题的两种O(M*N)解法
- 最长公共子序列(LCS)问题(非连续子序列)的两种解法
- LeetCode76 Minimum Window Substring(两种解法)
- (重刷)HDU 1874 畅通工程续 + HDU 2544 最短路 最短路水题,dijkstra解法。
- 计算字符串的相似度-两种解法
- 【LeetCode】3. Longest Substring Without Repeating Characters的两种解法
- [Wikioi 1294]全排列---两种不同的解法(复习)
- (两种解法)hdu 1540 Tunnel Warfare (线段树区间合并)
- HDU1050Moving Tables(贪心,树状数组两种解法)
- 算法系列之五:最长公共子序列(LCS)问题(非连续子序列)的两种解法
- hdu 4619 Warm up 2 (两种解法:1.并查集 2.最大独立集)