• 牛客网-华为-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;
    }
    
  • 相关阅读:
    开发一款即时通讯App,从这几步开始
    即时通讯App怎样才能火?背后的技术原理,可以从这5个角度切入
    快速搭建一个“微视”类短视频 App
    iOS Push详述,了解一下?
    怒刷3000条短视频后,我终于发现网红300万点赞的套路
    如何精准实现OCR文字识别?
    30分钟彻底弄懂flex布局
    渲染管道
    游戏引擎架构Note2
    浮点数的内存表示方法
  • 原文地址:https://www.cnblogs.com/xuyy-isee/p/10611199.html
Copyright © 2020-2023  润新知