PAT_1087. All Roads Lead to Rome

#include <iostream>
#include <string>
#include <string.h>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
struct City{
	string name;
	int happiness;
}city[205];  //数字与城市的映射
map<string,int> m;  //城市名字与数字的映射
int N,K,idx=1;  
int G[205][205];  //邻接矩阵表示图
bool vis[205];  //在当前dfs状态下某些点是否被访问过。
int minDist=9999999,maxHappiness=0,numCity=0,nextVertex[205],path[205];  //用来记录最优解情况下的各个数据
vector<int> diffRoute;	//用来记录可以到达终点的每一条路径的长度
void dfs(int v,int dist,int happiness,int depth)
{
	vis[v]=true;
	//cout<<"v="<<v<<" city[v].name="<<city[v].name<<",d="<<dist<<",h="<<happiness<<",depth="<<depth<<endl;
	if(dist>minDist)
		return;
	if(v==m["ROM"])
	{
		diffRoute.push_back(dist);
		if(dist<minDist)
		{
			minDist=dist;
			maxHappiness=happiness;
			numCity=depth;
			memcpy(path,nextVertex,sizeof(path));
		}
		else if(dist==minDist&&happiness>maxHappiness)
		{
			maxHappiness=happiness;
			numCity=depth;
			memcpy(path,nextVertex,sizeof(path));
		}
		else if(dist==minDist&&happiness==maxHappiness&&happiness/depth>maxHappiness/numCity)
		{
			numCity=depth;
			memcpy(path,nextVertex,sizeof(path));
		}
		return;
	}
	for(int i=1;i<idx;i++)
	{
		if(vis[i]==true||G[v][i]==-1)
			continue;
		nextVertex[v]=i;
		dfs(i,dist+G[v][i],happiness+city[i].happiness,depth+1);
		vis[i]=false;
	}
}
void outputRoute(int P[])
{
	int tempV=1;
	while(tempV!=m["ROM"])
	{
		cout<<city[tempV].name<<"->";
		tempV=P[tempV];
	}
	cout<<"ROM"<<endl;
}
int main()
{
	for(int i=0;i<205;i++)
		for(int j=0;j<205;j++)
			G[i][j]=-1;
	string st;
	cin>>N>>K>>st;

	m[st]=idx;
	city[1].name=st;
	city[1].happiness=0;
	idx++;

	string cityName;
	int hp;
	for(int i=0;i<N-1;i++)
	{
		cin>>cityName>>hp;
		m[cityName]=idx;
		city[idx].name=cityName;
		city[idx].happiness=hp;
		idx++;
	}
	string from,to;
	int dist;
	for(int i=0;i<K;i++)
	{
		cin>>from>>to>>dist;
		G[m[from]][m[to]]=dist;
		G[m[to]][m[from]]=dist;
	}
	dfs(1,0,0,0);
	int differentRoutes=0;
	sort(diffRoute.begin(),diffRoute.end());
	for(int i=0;i<diffRoute.size();i++)
	{
		if(diffRoute[i]==diffRoute[0])
			differentRoutes++;
		else
			break;
	}
	cout<<differentRoutes<<" "<<minDist<<" "<<maxHappiness<<" "<<maxHappiness/numCity<<endl;
	outputRoute(path);
}


这种类型的题做了不少了,如PAT1030 PAT1018 PAT1003 

这题的思路就是先把string类型代表的城市映射成int型,然后解法就与上面几道的思路相同。

采取DFS的策略,在遇到终点(ROM)之后判断是否为更优路径(比较路径,幸福值和,平均幸福和)

这题稍显麻烦的是要求出最短cost的路径总条数,我们只需要把所有可达终点的路径的长度都保存下来,排个序(升序),

那么与第一个路径长度相同的路径都要计入总条数内。

注意保存路径点的方式,我们用两个int 数组 path[] 和 nextVertex[]来保存,nextVertex用于dfs过程中的路径动态更新,path用于每次寻得最新更优解之后

将nextVertex数组中记录的点保存下来,这样dfs完毕之后path中保存的就是最优路径。注意memcpy的用法。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值