Hdu oj 2112 HDU Today

本文介绍了一个利用C++中的map容器进行字符串到整数映射的方法,并结合最短路径算法解决从起点到终点的最小成本问题。通过读取输入数据,将城市名映射为整数,然后使用Dijkstra算法计算最小路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:点击打开链接

关于C++中map的使用:点击打开链接

代码:

#include<stdio.h>
#include<string.h>
#include<string>
#include<map>//将字符串转化成数字 
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
char str1[30],str2[30];
int cost[150][150],d[150];
bool used[150];
void distr(int x,int y)
{
	for(int i=1;i<150;i++)//  !!
	{
		d[i]=INF;
		used[i]=false;
	}
	d[x]=0;
	while(true)
	{
		int v=-1;
		for(int u=1;u<=y;u++)
		if(!used[u]&&(v==-1||d[u]<d[v]))
		v=u;
		if(v==-1)
		break;
		used[v]=true;
		for(int u=1;u<=y;u++)
		d[u]=min(d[u],d[v]+cost[v][u]);
	}
	if(d[2]>=INF)
	printf("-1\n");
	else
	printf("%d\n",d[2]);
}
int main()
{
	int t;
	map<string,int>mp;
	while(~scanf("%d",&t))
	{
		if(t==-1)
		break;
		int i,j;
		int c;
		int flag=0;
		mp.clear();
		for(i=1;i<150;i++)
		    for(j=1;j<150;j++)
		    cost[i][j]=INF;  
		scanf("%s%s",str1,str2);
		if(strcmp(str1,str2))//判断起点和终点是否相等 
		flag=1;
		mp[str1]=1;
		mp[str2]=2;
		int count=3;
		for(i=0;i<t;i++)
		{
			scanf("%s%s%d",str1,str2,&c);
			if(!mp[str1])
			mp[str1]=count++;
			if(!mp[str2])
			mp[str2]=count++;
			cost[mp[str1]][mp[str2]]=cost[mp[str2]][mp[str1]]=c;
		}
		if(!flag)
		printf("0\n");
		else
		distr(1,count);
	}
	return 0;
}


 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值