码迷,mamicode.com
首页 > 其他好文 > 详细

usaco Bessie Come Home

时间:2015-09-07 22:32:58      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:

 题意是给一个牧场,牧场当中有好多牧区,每个牧区用一个英文字母表示,大写的字母代表的牧区里各有一头牛,小写的没有,大写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;
}

  

usaco Bessie Come Home

标签:

原文地址:http://www.cnblogs.com/modengdubai/p/4789967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!