1. 程式人生 > 其它 >資料結構 _ 基礎練習 _ 案例6-1.6 哈利·波特的考試

資料結構 _ 基礎練習 _ 案例6-1.6 哈利·波特的考試

技術標籤:資料結構_基礎

原題

點此連結1

題目分析

最短路徑問題,所求即 1.從哪個點開始 2.到最遠的點的距離 3.最短。
最一般的解法就是分別求出每個點到最遠點的距離,然後取最短。解題時需要考慮一個問題:
如何求解從點A開始的最遠點距離:在使用BFS搜尋的過程中,已訪問過的點同樣需要考慮,如果該點已訪問,但是本次訪問到這個點的路徑長度優於該結點記憶體有的最短路徑,則仍需要更新最短路徑並壓入佇列中

程式碼

#include <iostream>
#include <map>
#include <vector>
#include <queue>
using namespace std; typedef pair<int, int> TPair; // get the maximum length if bring obj is "st" int bfs(vector<vector<TPair>> &data, int st) { int max = -1; vector<int> visited(data.size(), -1); queue<int> q; visited[st] = 0; q.push(
st); while (!q.empty()) { auto node = q.front(); q.pop(); for (auto r : data[node]) { // important 1. if this flag have been visited before if (visited[r.first] != -1) { // but we still need to judge it. if it is lower when use "node -> r"
// then we still need to push it!!! if ((visited[node] + r.second) < visited[r.first]) { visited[r.first] = visited[node] + r.second; q.push(r.first); } } // important 2. have visited it before or not. else { visited[r.first] = visited[node] + r.second; q.push(r.first); } } } for (auto r : visited) { // if someone is -1, it means that can not get this obj!, so print 0 as the question say in the last. if (r == -1) return -1; else max = std::max(max, r); } // debug code // cout << st << " " << max << endl; return max; } int main() { // 1->n transform to 0->n-1 int n, e; cin >> n >> e; vector<vector<TPair>> data; data.resize(n); if (n == 0) cout << 0 << endl; // load the raw data, warning: flag transformation! for (auto i = 0; i < e; i++) { int a, b, c; cin >> a >> b >> c; data[a - 1].push_back({b - 1, c}); data[b - 1].push_back({a - 1, c}); } auto min = bfs(data, 0); auto minFlag = 0; for (auto i = 1; i < n; i++) { auto res = bfs(data, i); if (res == -1) { cout << 0 << endl; return 0; } if (res < min) { minFlag = i; min = res; } } cout << minFlag + 1 << " " << min << endl; return 0; }