牛客網-華為-2020屆校園招聘上機考試-2


題目描述
平原上,一群蜜蜂離開蜂巢采蜜,要連續采集5片花叢后歸巢。
已知5片花叢相對蜂巢的坐標,請你幫它們規划一下到訪花叢的順序,以使飛翔總距離最短。

輸入描述
以蜂巢為平面坐標原點的5片花叢A、B、C、D、E的坐標,坐標值為整數。
輸出描述
從出發到返回蜂巢最短路徑的長度取整值,取整辦法為舍棄小數點后面的值。

示例1
輸入
200 0 200 10 200 50 200 30 200 25
輸出
456
說明
樣例中的10個數,相鄰兩個分別為一組,表示一個花叢相對蜂巢的坐標:A(x1, y1)、B(x2, y2)、C(x3, y3)、D(x4, y4)、E(x5, y5),分表代表x1,y1,x2,y2,x3,y3,x4,y4,x5,y5

1.思考

  • 一開始想到的是Hamilton回路,但是現在還沒有復習到這一塊,就無從下手,於是就先做第3題了。后來證實直接用暴力搜索遍歷一遍的方法也是可以通過的。
  • 代碼以后再補上。
    ------------------------------------------------------ 后期補上 ----------------------------------------------------------------
  • 由於只有5個花叢,其實用DFS或者BFS遍歷所需要的時間也不高的,下面就使用了DFS遍歷來得到最優解;
  • 先通過getline()得到輸入的坐標字符串,再用函數Apart()將字符串轉變為數字坐標,並兩個一組存放在coor中。A、B、C、D、E分別對應的index為1、2、3、4、5,其中index=0的是原點坐標(0,0);
  • 通過DFS將所有可能的路線都進行一遍,並選出路線最短的。其中coor為所有花叢的坐標;visit用來記錄該花叢是否訪問過,若去過則對應位置為1,否則為0;node為下一個要訪問的花叢的編號;
  • 如果要對遍歷進行優化的話,用“分支界限法”可以減少遍歷的數量,那這邊就要改成BFS進行遍歷比較合適。

2.實現

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
using namespace std;

void Apart(string s, vector<vector<int>>& coor)
{
	int n1=0, n2=0;
	int i = 0, len = s.size();
	while (i<len)
	{
		n1 = 0, n2 = 0;
		while (s[i] != ' ')
		{
			n1 = n1 * 10 + (s[i] - '0');
			i++;
		}
		i++;
		while (s[i] != ' ' && i<len)
		{
			n2 = n2 * 10 + (s[i] - '0');
			i++;
		}
		i++;
		coor.push_back(vector<int> {n1, n2});
	}
}

vector<int> DFS(vector<vector<int>> coor, vector<int> visit, int node)
{
	visit[node] = 1;
	int x = coor[node][0], y = coor[node][1], xi, yi;
	if (accumulate(visit.begin(), visit.end(), 0) == visit.size())
		return vector<int>{ int(sqrt( pow(x, 2) + pow(y, 2) )) };

	int dis;
	vector<int> res, d;
	int n = visit.size();
	for (int i = 0; i < n; i++){
		if (visit[i] == 0){
			xi = coor[i][0];
			yi = coor[i][1];
			d = DFS(coor, visit, i);
			for (int dd : d){
				dis = sqrt(pow((x - xi), 2) + pow((y - yi), 2)) + dd;
				res.push_back(dis);
			}
		}
	}
	return res;
}

int main(){
	string input;

	while (getline(cin, input)){
		vector<vector<int>> coor;
		coor.push_back(vector<int> {0, 0});
		Apart(input, coor);

		//DFS
		int node = 5, res;
		vector<int> visit(node+1, 0);
		vector<int> dis;
		dis = DFS(coor, visit, 0);
		res = *min_element(dis.begin(), dis.end());
		cout << res << endl;
	}

	return 0;
}


免責聲明!

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



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