Graduation trip to save money problems

A research laboratory brings together monks from different provinces. Just before graduation, Yuan proposed to conduct a small group graduation trip, to everyone's career research Monk leave a good mark. Mike felt very good, he represents all day thinking about how to play the strong support. One day, Li teacher on a business trip, nothing else, in turn begun to wander, wander to travel issues: from Fuzhou, and finally back to Fuzhou, how to travel between (Nanchang, Nanjing, Hefei, Taiyuan, Zhengzhou) provincial capitals most provinces tolls? Then wrote this C ++ code to the computer have solutions. This in mind, it is useful for the future.

Code ideas: the journey as well as among all cities can be seen as a fully connected undirected weighted graph, depth-first search starting from a starting point to find the smallest weight ring.

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

struct City//城市节点,记录名称以及是否被访问
{
	bool visited;
	string name;
	City():visited(false),name("no name"){}
};

enum CityName{
	FuZhou		=	0,
	NanChang	=	1,
	NanJing		=	2,
	HeFei		=	3,
	TaiYuan		=	4,
	ZhengZhou	=	5,
	TotCity		=	6,
};

const static int TravelPrice[TotCity][TotCity]={//各个城市之间的车票或者飞机票价格
	{0,		160,	314,	357,	430,	451},
	{160,	0,		369,	316,	235,	291},
	{314,	369,	0,		67,		395,	317},
	{357,	316,	67,		0,		278,	307},
	{430,	235,	395,	278,	0,		257},
	{451,	291,	317,	307,	257,	0}
}; 

const static string CityName_s[TotCity]={
	"FuZhou","NanChang","NanJing","HeFei","TaiYuan","ZhengZhou"
};

class Solution {
public:
	string SearchLowestPricePath(){
		string path, optPath;            //可能的路径以及最佳路径
		int price=0, optPrice=INT_MAX;   //可能的价格以及最佳价格
		vector<City> ourCity(TotCity);
		for(int i=0; i<TotCity; i++)
			ourCity[i].name=CityName_s[i];
		path="start";
		Travel(ourCity, FuZhou, path, optPath, price, 5, optPrice);//5块乘地铁
		return optPath;
	}
	void Travel(vector<City> visCity, int lastCity, string path, string& optPath, int Price, int curPrice, int& optPrice){	
		visCity[lastCity].visited=true;//上一城市已游玩
		path=path+" -> "+CityName_s[lastCity];//路径历史
		Price+=curPrice;
		for(int i=0; i<TotCity; i++){
			if(!visCity[i].visited)
				break;
			else if(i==TotCity-1){//递归基,所有城市都已访问,回福州
				Price+=TravelPrice[lastCity][FuZhou];
				path=path+" -> "+CityName_s[FuZhou]+" "+to_string(Price);
				if(Price<optPrice){
					optPrice=Price;
					optPath=path;
				}
				return;
			}
		}
		for(int i=1; i<TotCity; i++){//去下一个城市
			if(visCity[i].visited)//去过的不去
				continue;
			Travel(visCity, i, path, optPath, Price, TravelPrice[lastCity][i], optPrice);
		}
	}
};


int main()
{
	Solution c;
	cout<<c.SearchLowestPricePath()<<endl;
	system("pause");
	return 0;
}

I want to graduate.

Published 18 original articles · won praise 0 · Views 789

Guess you like

Origin blog.csdn.net/afiguresomething/article/details/103205853