2019阿里校招測評題,光明小學完全圖最短路徑問題


題目:

光明小學的小朋友們要舉行一年一度的接力跑大賽了,但是小朋友們卻遇到了一個難題:設計接力跑大賽的線路,你能幫助他們完成這項工作么?
光明小學可以抽象成一張有N個節點的圖,每兩點間都有一條道路相連。光明小學的每個班都有M個學生,所以你要為他們設計出一條恰好經過M條邊的路徑。
光明小學的小朋友們希望全盤考慮所有的因素,所以你需要把任意兩點間經過M條邊的最短路徑的距離輸出出來以供參考。

你需要設計這樣一個函數:
res[][] Solve( N, M, map[][]);
注意:map必然是N * N的二維數組,且map[i][j] == map[j][i],map[i][i] == 0,-1e8 <= map[i][j] <= 1e8。(道路全部是無向邊,無自環)2 <= N <= 100, 2 <= M <= 1e6。要求時間復雜度控制在O(N^3*log(M))。

map數組表示了一張稠密圖,其中任意兩個不同節點i,j間都有一條邊,邊的長度為map[i][j]。N表示其中的節點數。
你要返回的數組也必然是一個N * N的二維數組,表示從i出發走到j,經過M條邊的最短路徑
你的路徑中應考慮包含重復邊的情況。

 

參考:https://blog.csdn.net/u012465304/article/details/81180707

 

思路:其實就是M步無向圖的最短路徑遍歷,設置步數為M,當M步到達所需要的end點且distance較小則更新,遞歸實現。

 

// Study.cpp: 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <string>
#include <algorithm>
#include <sstream>

#define INT_MAX 2147483647 // maximum (signed) int value
#define INT_MIN (-2147483647 - 1) // minimum (signed) int value

using namespace std;

vector<vector<int>> result;
vector<vector<int>> map;
int minStep = INT_MAX;

void dfs(int start, int end, int N ,int M ,int dis ,int steps)
{
if (steps == M)
{
//剛剛好 M步 到達所需要的end 且路徑較短,則更新數值
if (start == end && dis < minStep)
minStep = dis;
return;
}

int rdis;
for (int next = 0; next < N; next++)
{
if (next == start)
continue;
rdis = dis + map[start][next];
dfs(next, end, N, M, rdis,steps+1);
}
}
vector<vector<int>> solution(int N, int M)
{
result = vector<vector<int>> (N, vector<int>(N, 0));
int dis = 0;
queue<vector<int>> Que;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
// 求從 i -> j 的最短路徑
dfs(i, j, N, M, 0, 0);
result[i][j] = minStep;
minStep = INT_MAX;
}
}

return result;
}
int main()
{
int N, M;
cin >> N >> M;
int tmp;
map = vector<vector<int>> (N, vector<int>(N, 0));
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cin >> tmp;
map[i][j] = tmp;
}
}

solution(N, M);
for (auto g : result)
{
for (auto i : g)
cout << i << " ";
cout << endl;
}
system("pause");
return 0;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM