******************************************************************************************************************************** 圖算法 ******************************************************************************************************************************** ------------------------------------------ 深度優先搜索 DFS // 是否連通圖 typedef vector<int> vi; typedef vector<vi> vvi; int N; // number of vertices vvi W; // graph vi V; // V is a visited flag void dfs(int i) { if(!V[i]) { V[i] = true; for_each(all(W[i]), dfs); } } bool check_graph_connected_dfs() { int start_vertex = 0; V = vi(N, false); dfs(start_vertex); return (find(all(V), 0) == V.end()); } ------------------------------------------ 廣度優先搜索 BFS // BFS通常會使用queue queue 方法:front(), back(), push() (== push_back()), pop (== pop_front()),empty(), size() // 是否連通圖 int N; // number of vertices vvi W; // lists of adjacent vertices bool check_graph_connected_bfs() { int start_vertex = 0; vi V(N, false); queue<int> Q; Q.push(start_vertex); V[start_vertex] = true; while(!Q.empty()) { int i = Q.front(); // get the tail element from queue Q.pop(); // tr(W[i], it) for (vi::iterator it = W[i].begin(); it != W[i].end(); it++) { if(!V[*it]) { V[*it] = true; Q.push(*it); } } } return (find(all(V), 0) == V.end()); } ------------------------------------------ dijkstra 圖最短路徑算法 該算法類似於bfs,不過總是優先遍歷當前路徑權值最小的點 用set實現(用set的自排序功能模擬優先級隊列)版本 typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<vii> vvii; vvii G; void dijkstra_bfs_set() { vi D(N, 987654321); // start vertex set<ii> Q; // 起點是0端點 D[0] = 0; Q.insert(ii(0,0)); while(!Q.empty()) { // again, fetch the closest to start element // from “queue” organized via set ii top = *Q.begin(); Q.erase(Q.begin()); int v = top.second, d = top.first; // here we do not need to check whether the distance // is perfect, because new vertices will always // add up in proper way in this implementation for (vii::iterator it = G[v].begin(); it != G[v].end(); it++) { int v2 = it->first, cost = it->second; if(D[v2] > D[v] + cost) { // this operation can not be done with priority_queue, // because it does not support DECREASE_KEY if(D[v2] != 987654321) { Q.erase(Q.find(ii(D[v2],v2))); } D[v2] = D[v] + cost; Q.insert(ii(D[v2], v2)); } } } }
圖算法中STL的應用
接前面兩篇STL的使用摘要再加一點圖算法中STL的使用,
攝於csdn blog強大的不換行功能,還是直接代碼格式貼上來吧
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.