hdu 2112 HDU Today

本文探讨了使用算法优化解决输入中起点和终点相同的路径问题,通过构建地图数据结构并实现Dijkstra算法来寻找最短路径。文章详细介绍了数据预处理、图构建过程以及算法应用实例,旨在提供一种有效解决特定路径问题的方法。

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

输入当中有起点和终点相同的,所以使用map时要注意

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int N=205;
const int inf=1000;
map<string,int>a;

int main()
{
    int tot,i,j,k,n,ans,t,st,ed,g[N][N];
    char s1[50],s2[50];
    while(~scanf("%d",&n))
    {
        if(n==-1) break;
        for(i=0; i<=200; i++)
            for(j=0; j<=200; j++)
            {
                if(i==j) g[i][j]=0;
                else g[i][j]=inf;
            }
        tot=1;
        a.clear();
        scanf("%s %s ",s1,s2);
        if(a[s1]==0)
        {
            a[s1]=tot;
            tot++;
        }
        st=a[s1];
        if(a[s2]==0)
        {
            a[s2]=tot;
            tot++;
        }
        ed=a[s2];
        for(i=0; i<n; i++)
        {
            scanf("%s %s %d",s1,s2,&t);
            if(a[s1]==0)
            {
                a[s1]=tot;
                tot++;
            }
            if(a[s2]==0)
            {
                a[s2]=tot;
                tot++;
            }
            g[a[s1]][a[s2]]=min(g[a[s1]][a[s2]],t);
            g[a[s2]][a[s1]]=g[a[s1]][a[s2]];
        }

        for(k=1; k<=tot; k++)
            for(i=1; i<=tot; i++)
            {
                for(j=1; j<=tot; j++)
                    if(g[i][j]>g[i][k]+g[k][j])
                        g[i][j]=g[i][k]+g[k][j];
            }

        if(g[st][ed]==inf)
            printf("-1\n");
        else   printf("%d\n",g[st][ed]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值