usaco Bessie Come Home

 题意是给一个牧场,牧场当中有好多牧区,每个牧区用一个英文字母表示,大写的字母代表的牧区里各有一头牛,小写的没有,大写Z代表牛吃饭的地方。

牛以相同的速度往吃饭的地方走,问哪个牧区的牛先到,并输出这头牛走过距离

解法是以Z为起点求一遍单源最短路径。找到里的最近的那个大写字母所代表的那个牧场。

/*
ID: modengd1
PROG: comehome
LANG: C++
*/
#include <iostream>
#include <stdio.h>
#include <queue>
#include <memory.h>
#define INF 2139062143
using namespace std;
int input[53][53];
int N;

int getindex(char x)
{
    if(x<='z'&&x>='a')//小写字母标号0-25
        return x-'a';
    return x-'A'+26;//大写字母26-51
}
struct node
{
    int E,W;
    node(int ee,int ww)
    {
        E=ee;W=ww;
    }
    node(){}
    bool friend operator<(node n1,node n2)
    {
        return n1.W>n2.W;
    }
};
void Dijiskra(int x)
{
    int dist[56];
    memset(dist,0x7f,sizeof(dist));//以字节为单位初始化,得到的数组中每个int值为2139062143,也就是INF
    priority_queue<node> Q;
    Q.push(node(x,0));
    node now;
    while(!Q.empty())
    {
        now=Q.top();
        Q.pop();
        if(now.E>25&&now.E!=x)//找到了一个大写字母代表的牧区就输出并返回,因为dijiskra算法按照最短路径升序找最短
        {
            printf("%c %d\n",now.E+'A'-26,now.W);
            return;
        }
        for(int i=0;i<52;i++)
        {
            if(input[now.E][i]!=INF&&dist[i]>now.W+input[now.E][i])//小于当前dist数组中的值再入队列
            {
                Q.push(node(i,now.W+input[now.E][i]));
                dist[i]=now.W+input[now.E][i];
            }
        }
    }
}
int main()
{
    freopen("comehome.in","r",stdin);
    freopen("comehome.out","w",stdout);
    memset(input,0x7f,sizeof(input));
    scanf("%d",&N);
    getchar();
    char ch1,ch2;
    int temp,a,b;
    for(int i=0;i<N;i++)
    {
        ch1=getchar();
        getchar();
        ch2=getchar();
        getchar();
        scanf("%d",&temp);
        getchar();
        if(temp<input[getindex(ch1)][getindex(ch2)])//输入
        {
            input[getindex(ch1)][getindex(ch2)]=temp;
            input[getindex(ch2)][getindex(ch1)]=temp;
        }
    }
    Dijiskra(51);
    return 0;
}

  

转载于:https://www.cnblogs.com/modengdubai/p/4789967.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值