USACO section 2.4 Bessie Come Home(最短路)

PostgreSQL性能优化:如何搭建监控体系? 本文系统讲解如何构建企业级PostgreSQL监控体系,覆盖四大核心维度:基础设施层、数据库实例层、会话与查询层、对象与存储层。通过Prometheus+Grafana+ELK等工具链实现指标采集、可视化与告警闭环管理,详细解析关键监控指标、部署方法及告警策略设计,帮助DBA快速定位慢查询、连接泄漏、存储膨胀等典型故障,构建"看得见、管得住、防得早"的数据库运维能力。 阅读详情
Bessie Come Home
Kolstad & Burch

It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure out which one cow gets to the barn first (the supplied test data will always have exactly one fastest cow).

Between milkings, each cow is located in her own pasture, though some pastures have no cows in them. Each pasture is connected by a path to one or more other pastures (potentially including itself). Sometimes, two (potentially self-same) pastures are connected by more than one path. One or more of the pastures has a path to the barn. Thus, all cows have a path to the barn and they always know the shortest path. Of course, cows can go either direction on a path and they all walk at the same speed.

The pastures are labeled `a'..`z' and `A'..`Y'. One cow is in each pasture labeled with a capital letter. No cow is in a pasture labeled with a lower case letter. The barn's label is `Z'; no cows are in the barn, though.

PROGRAM NAME: comehome

INPUT FORMAT

 

Line 1:Integer P (1 <= P <= 10000) the number of paths that interconnect the pastures (and the barn)
Line 2..P+1:Space separated, two letters and an integer: the names of the interconnected pastures/barn and the distance between them (1 <= distance <= 1000)

SAMPLE INPUT (file comehome.in)

5
A d 6
B d 3
C e 9
d Z 8
e Z 3

OUTPUT FORMAT

A single line containing two items: the capital letter name of the pasture of the cow that arrives first back at the barn, the length of the path followed by that cow.

SAMPLE OUTPUT (file comehome.out)

B 11


思路:直接输入,用数组存,求出所有通路的值,最后扫描一遍,输出答案具体看代码

 

 未修改前4次方

/*
 ID:nealgav1
 LANG:C++
 PROG:comehome
*/
#include<fstream>
#include<cstring>
#include<cstdio>
using namespace std;
ifstream cin("comehome.in");
ofstream cout("comehome.out");
const int mm=11000;
const int oo=1e9;
int dist[210][210];
int dag()
{
  for(int l='A';l<='z';l++)///层数,不加会错
  for(int i='A';i<='z';i++)///连接
  for(int j='A';j<='z';j++)
  { if(i==j)continue;
    for(int k='A';k<='z';k++)
    { if(dist[i][k]&&dist[k][j])
      {
        if(dist[i][j])
        dist[i][j]=dist[j][i]=min(dist[i][j],dist[i][k]+dist[k][j]);
        else dist[i][j]=dist[j][i]=dist[i][k]+dist[k][j];
      }
    }
  }
  int mlen=oo;char ans;
  for(int i='A';i<='Y';i++)
  if(dist[i]['Z'])
  {
    if(dist[i]['Z']<mlen)mlen=dist[i]['Z'],ans=i;
  }
  cout<<ans<<" "<<mlen<<"\n";
  return mlen;
}
int main()
{int m;
 char a,b;int c;
 cin>>m;
 memset(dist,0,sizeof(dist));
 for(int i=0;i<m;i++)
 {
   cin>>a>>b>>c;
   if(dist[a][b]>c||dist[a][b]==0)
   {dist[a][b]=c;dist[b][a]=c;}
 }
 dag();
 ///cout<<dag()<<"\n";
}

修改后3次方算法,其实是上面的算法用的不正确
 

/*
 ID:nealgav1
 LANG:C++
 PROG:comehome
*/
#include<fstream>
#include<cstring>
#include<cstdio>
using namespace std;
ifstream cin("comehome.in");
ofstream cout("comehome.out");
const int mm=11000;
const int oo=1e9;
int dist[210][210];
int dag()
{
  for(int k='A';k<='z';k++)
  for(int i='A';i<='z';i++)///连接
  for(int j='A';j<='z';j++)
  { if(i==j)continue;
     if(dist[i][k]&&dist[k][j])
      {
        if(dist[i][j])
        dist[i][j]=dist[j][i]=min(dist[i][j],dist[i][k]+dist[k][j]);
        else dist[i][j]=dist[j][i]=dist[i][k]+dist[k][j];
      }
  }
  int mlen=oo;char ans;
  for(int i='A';i<='Y';i++)
  if(dist[i]['Z'])
  {
    if(dist[i]['Z']<mlen)mlen=dist[i]['Z'],ans=i;
  }
  cout<<ans<<" "<<mlen<<"\n";
  return mlen;
}
int main()
{int m;
 char a,b;int c;
 cin>>m;
 memset(dist,0,sizeof(dist));
 for(int i=0;i<m;i++)
 {
   cin>>a>>b>>c;
   if(dist[a][b]>c||dist[a][b]==0)
   {dist[a][b]=c;dist[b][a]=c;}
 }
 dag();
 ///cout<<dag()<<"\n";
}


Bessie Come Home
Russ Cox

We use the Floyd-Warshall all pairs shortest path algorithm to calculate the minimum distance between the barn and all other points in the pasture. Then we scan through all the cow-containing pastures looking for the minimum distance.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>

#define INF 60000	/* bigger than longest possible path */

int dist[52][52];

int
char2num(char c)
{
    assert(isalpha(c));

    if(isupper(c))
	return c-'A';
    else
	return c-'a'+26;
}

void
main(void)
{
    FILE *fin, *fout;
    int i, j, k, npath, d;
    char a, b;
    int m;

    fin = fopen("comehome.in", "r");
    fout = fopen("comehome.out", "w");
    assert(fin != NULL && fout != NULL);

    for(i=0; i<52; i++)
    for(j=0; j<52; j++)
	dist[i][j] = INF;

    for(i=0; i<26; i++)
	dist[i][i] = 0;

    fscanf(fin, "%d\n", &npath);
    for(i=0; i<npath; i++) {
	fscanf(fin, "%c %c %d\n", &a, &b, &d);
	a = char2num(a);
	b = char2num(b);
	if(dist[a][b] > d)
	    dist[a][b] = dist[b][a] = d;
    }

    /* floyd warshall all pair shortest path */
    for(k=0; k<52; k++)
    for(i=0; i<52; i++)
    for(j=0; j<52; j++)
	if(dist[i][k]+dist[k][j] < dist[i][j])
	    dist[i][j] = dist[i][k]+dist[k][j];

    /* find closest cow */
    m = INF;
    a = '#';
    for(i='A'; i<='Y'; i++) {
	d = dist[char2num(i)][char2num('Z')];
	if(d < m) {
	    m = d;
	    a = i;
	}
    }

    fprintf(fout, "%c %d\n", a, m);
    exit(0);
}

Analysis of and code for Bessie Come Home by Wouter Waalewijn of The Netherlands

When looking at the problem the first thing you can conclude is that for the solution you will need to know all the distances from the pastures to the barn. After calculating them you only have to check all these distances and pick out the nearest pasture with a cow in it, and that's all.

Because the amount of vertices (=pastures+barn) is small, running Floyd/Warshall algorithm will solve the problem easily in time. If you think programming Floyd/Warshall is easier than Dijkstra, just do it. But you can also solve the problem running Dijkstra once, which of course speeds up your program quite a bit. Just initialise the barn as starting point, and the algorithm will find the distances from the barn to all the pastures which is the same as the distances from all the pastures to the barn because the graph is undirected. Using dijkstra for the solution would make far more complex data solvable within time. Here below you can see my implementation of this solution in Pascal. It might look big, but this way of partitioning your program keeps it easy to debug.

Var Dist:Array [1..58] of LongInt;      {Array with distances to barn}
    Vis :Array [1..58] of Boolean;      {Array keeping track which
pastures visited}
    Conn:Array [1..58,1..58] of Word;   {Matrix with length of edges, 0 = no edge}

Procedure Load;
Var TF   :Text;
    X,D,E:Word;
    P1,P2:Char;

Begin
 Assign(TF,'comehome.in');
 Reset(TF);
 Readln(TF,E);                          {Read number of edges}
 For X:=1 to E do
 Begin
  Read(TF,P1);                          {Read both pastures and edge
length}
  Read(TF,P2);
  Read(TF,P2);      {Add edge in matrix if no edge between P1 and P2 yet or}
  Readln(TF,D);     {this edge is shorter than the shortest till now}
  If (Conn[Ord(P1)-Ord('A')+1,Ord(P2)-Ord('A')+1]=0) or
     (Conn[Ord(P1)-Ord('A')+1,Ord(P2)-Ord('A')+1]>D) then
  Begin
   Conn[Ord(P1)-Ord('A')+1,Ord(P2)-Ord('A')+1]:=D;
   Conn[Ord(P2)-Ord('A')+1,Ord(P1)-Ord('A')+1]:=D;
  End;
 End;
 Close(TF);
 For X:=1 to 58 do
  Dist[X]:=2147483647;                  {Set all distances to infinity}
 Dist[Ord('Z')-Ord('A')+1]:=0;          {Set distance from barn to barn to 0}
End;

Procedure Solve;
Var X,P,D:LongInt;                      {P = pasture and D = distance}

Begin
 Repeat
  P:=0;
  D:=2147483647;
  For X:=1 to 58 do                     {Find nearest pasture not
visited yet}
   If Not Vis[X] and (Dist[X]<D) then
   Begin
    P:=X;
    D:=Dist[X];
   End;
  If (P<>0) then
  Begin
   Vis[P]:=True;                        {If there is one mark it
visited}
   For X:=1 to 58 do                    {And update all distances}
    If (Conn[P,X]<>0) and (Dist[X]>Dist[P]+Conn[P,X]) then
     Dist[X]:=Dist[P]+Conn[P,X];
  End;
 Until (P=0);                {Until no reachable and unvisited pastures
left}
End;

Procedure Save;
Var TF  :Text;
    X,BD:LongInt;                       {BD = best distance}
    BP  :Char;                          {BP = best pasture}

Begin
 BD:=2147483647;
 For X:=1 to 25 do                      {Find neares pasture}
  If (Dist[X]<BD) then
  Begin
   BD:=Dist[X];
   BP:=Chr(Ord('A')+X-1);
  End;
 Assign(TF,'comehome.out');
 Rewrite(TF);
 Writeln(TF,BP,' ',BD);                 {Write outcome to disk}
 Close(TF);
End;

Begin
 Load;
 Solve;
 Save;
End.

 

 

 

 

【教程4>第4章>第15节】基于FPGA的costas环的设计构架 目录1.costas环的整体实现结构2. FPGA设计构架3.参考文献 Costas 环是一种用于载波同步的闭环反馈控制系统,主要应用于通信系统中的相干解调。其基本原理是通过鉴相器(Phase Detector,PD)比较接收信号与本地载波信号的相位差,将这个相位差信息经过环路滤波器(Loop Filter,LF)滤波后,去控制数控振荡器(Numerically Controlled Oscillator,NCO)的输出频率和相位,使得本地载波能够跟踪接收信号的载波,最终实现载波同步。我们在《F 阅读详情

相关推荐

Trae+Playwright MCP自动化测试全流程指南:从环境搭建到智能体运行

本文提供了一份详细的Trae与Playwright MCP集成指南,涵盖从Node.js、Python环境搭建到智能体创建的全流程。通过结合MCP协议,AI智能体能够理解任务并驱动Playwright执行复杂的浏览器自动化操作,实现从网页数据抓取到端到端测试的智能工作流。

banana的博客 531

Bessie Come Home(最短路 + Floyd)

Bessie Come HomeKolstad &amp; Burch It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure out w...

Simone chou... 240

工业以太网通讯Profinet协议详解

Profinet是通过西门子控制系统被广泛使用的工业通信协议,是一种较新的,基于以太网的工业通讯协议。

mydatai的专栏 8851

Bessie Come Home

题目描述: It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure out which one cow gets to the barn fi...

versionwen的博客 275

【Flink cdc】Data row is smaller than a column index, internal schema representation is probably xxx

翻译一下:当scan.startup.mode=EARLIEST_OFFSET时,如果在最早的offset之后表结构有过变化就无法支持。原因应该是在binlog 的earliest_offset之后,表结构被修改过。我的解决方案:source配置中使用。mysql source配置使用。,以时间戳为消费依据。

integrity 2085

<Verilog实现除法器> Verilog实现牛顿-拉夫逊(Newton-Raphson)除法器

阿斯顿阿斯顿啊啊是打发士大夫

IC跳跳鱼的博客 3586

USACO 2.4 comehome(Bessie Come Home)

目录 目录 题目描述 程序名 输入格式 输入样例 输出格式 输出样例 解题思路 主要步骤 代码 题目描述 晚餐时间到了,奶牛们都在各自的牧场里。农夫约翰按响了铃,它们就开始往谷仓走去。你的工作是确定哪一头奶牛会先到达谷仓(提供的测试数据中总是有一头最快的奶牛)。 在挤奶过程中(晚餐前),每头奶牛都在自己的牧场上,尽管有些牧场上没有奶牛。每个牧场都由一条条道路和一个或...

qq_42989316的博客 841

ANSYS命令流黑箱揭秘:流体渗透压力载荷的七种收敛优化策略

本文深入解析ANSYS Workbench中流体渗透压力载荷的七种收敛优化策略,重点探讨接触探测点迭代逻辑、PPCN阈值动态调整及FPAT参数优化等关键技术。通过命令流示例和实战技巧,帮助工程师有效解决流体与结构相互作用仿真中的收敛难题,提升计算效率和精度。

weixin_29274337的博客 523

Bessie Come Home回家 NOIP题解

最短路径算法

幸福回头的博客 508

74.9008深度刷机原理|高通QPST/Firehose底层刷写协议详解

移动设备刷机与底层维修技术指南 本文为移动设备维修人员和高级玩家提供全面的刷机与底层维修技术指南,涵盖高通、联发科和苹果A系列芯片的主要操作。 主要内容 核心操作:Bootloader解锁、Fastboot刷写、EDL深度修复、iTunes DFU模式恢复和分区表重建 适用场景:系统故障修复、底层损坏恢复、安全限制解除、系统降级和深度硬件维修 关键技术:详细解析刷机协议栈层级、关键分区作用和刷机安全机制 操作步骤: 环境搭建与驱动安装 Bootloader解锁(以小米为例) 高通机型系统刷写 苹果设备DFU

2601_95651806的博客 205

华为OD机试真题 新系统2026-04-01 Python&JS【计算数列位置N的值】

如果其前面的M个元素中,存在值相同的元素,则该位置上的数值等于前面M个数中最大的数值与最小的数值之如果其前面的M个元素中,不存在值相同的元素,则该位置上的数值等于前面M个数中最大的数值与最小的数值之差;1、输入M、N两个数,则按照以下规则形成一个数列;两个整数,用逗号分割,分别表示M和N。一个整数,表示数列第N个位置上的数值。2、数列的前M个元素的值为1到M;请计算该数列第N个位置上的数值。N取值范围:1<= N<=50。M取值范围:3<=M<=10。

MISAYAONE的博客 3218

USACO / Bessie Come Home( Dijkstra标程 )

Bessie Come Home 回家 现在是晚餐时间,而母牛们在外面分散的牧场中。 农民约翰按响了电铃,所以她们开始向谷仓走去。 你的工作是要指出哪只母牛会最先到达谷仓(在给出的测试数据中,总会有且只有一只最快的母牛)。 在挤奶的时候(晚餐前),每只母牛都在她自己的牧场上,一些牧场上可能没有母牛。 每个牧场由一条条道路和一个或多个牧场连接(可能包括自己)。 有时,

1194

自然语言处理之话题建模:BERTopic模型详解

BERTopic是一种基于BERT的先进话题建模技术,它结合了BERT的语义理解能力和非参数聚类算法HDBSCAN的灵活性,能够生成高质量、语义丰富的话题。与传统的LDA(Latent Dirichlet Allocation)话题模型相比,BERTopic能够更好地捕捉文本的复杂语义结构,因为它利用了预训练的BERT模型来嵌入文本,从而在话题建模中引入了深度学习的力量。聚类是无监督学习的一种,其目标是将数据集中的样本按照相似性进行分组,每个组称为一个“簇”。

zhubeibei168的博客 4538

USACO-Section 2.4 Bessie Come Home(最短路[Dijkstra])

从Z点开始,开始更新各点到Z点的最短距离,第一个距离Z点最短并且未用的点如果存在奶牛,则其即为答案

idealism_xxm的专栏 711

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

USACO - Chapter2 Section 2.4 - Bessie Come Home

Bessie Come Home

zhuo1ang的博客 381

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

USACO Section 2.4 Bessie Come Home(dijkstra)

Bessie Come HomeKolstad & Burch It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure ou...

angtongyou1893的博客 214

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

USACO section2.4 Bessie Come Home题解&代码

模拟题啦,floyd得到最短路,然后直接找到最短可达路径即可 注意点是’M’和’m’并不是同一个牧场,区分大小写的是不同牧场,因此共有51个牧场和1个谷仓/* ID:rainbow16 LANG:C++ TASK:comehome */ #include<iostream> #include<stdio.h> #include<string.h> #define MAX 0xfffffff usi

Rainbow6174's home 1244

Usaco Training Section 2.4 Bessie Come Home

求A~Z、a~z这52个点,求A~Y到Z的最短距离。 这题就是正常的最短路题,点数也很少。floyd和spfa都能过。 注意:两点间可能有不止一条边。 一开始没注意这一点,wa了一次。。。 floyd: #include&lt;bits/stdc++.h&gt; using namespace std; int d[53][53]; int main() {     freopen(...

Monster的博客 304

USACO-Section2.4 Bessie Come Home【dijkstra算法】

题目描述: 现在是晚餐时间,而母牛们在外面分散的牧场中。 农民约翰按响了电铃,所以她们开始向谷仓走去。 你的工作是要指出哪只母牛会最先到达谷仓(在给出的测试数据中,总会有且只有一只速度最快的母牛)。 在挤奶的时候(晚餐前),每只母牛都在她自己的牧场上,一些牧场上可能没有母牛。 每个牧场由一条条道路和一个或多个牧场连接(可能包括自己)。 有时,两个牧场(可能是字母相同的)之间会有超过一条道路相连。

tjj1998的博客 365

usaco-Section 2.4-Bessie Come Home

Bessie Come HomeKolstad & Burch It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure out whi...

weixin_30423977的博客 106

USACO Training Section 2.4 Bessie Come Home

[url="http://ace.delos.com/usacoprob2?a=nNDUxS4hI8l&S=comehome"]英文原题[/url] [url="http://www.wzoi.org/usaco/12%5C304.asp"]中文题译[/url] 加权图上的单源最短路径。本身是最简单的。题目加了一些限制,如,节点从a-z,A-Z编号,最后只输出大写编号的节点到Z节点的最短...

山中竹笋 525

USACO SECTION 2.4 Bessie Come Home

Bessie Come Home Kolstad & Burch It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure out whic

239

USACO Section 2.4 Bessie Come Home (comehome)

Bessie Come Home Kolstad & Burch It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure ...

weixin_30419799的博客 145

USACO Section 2.4

USACO Section 2.4 The Tamworth Two/* ID: beihai2013 TASK: ttwo LANG: C++ */ /* 刚开始想复杂了,想通过记录数组然后求牛或者人经过此点的时间戳来求周期,然后求一个通项 后面发现这样的讨论不仅复杂,而且容易出现十分多的情况 然后仔细一想,假设是有人和牛周期的话,他们分别得周期不

beihai2013 286

2.4.4 Bessie Come Home 回家

Description 现在是晚餐时间,而母牛们在外面分散的牧场中。 农民约翰按响了电铃,所以她们开始向谷仓走去。 你的工作是要指出哪只母牛会最先到达谷仓(在给出的测试数据中,总会有且只有一只速度最快的母牛)。 在挤奶的时候(晚餐前),每只母牛都在她自己的牧场上,一些牧场上可能没有母牛。 每个牧场由一条条道路和一个或多个牧场连接(可能包括自己)。 有时,两个牧场(可能是自我相同的)之间会有超过一...

Akatsuki 789

Bessie Come Home 贝西回家

Description 现在是晚餐时间,而母牛们在外面分散的牧场中。农民约翰按响了电铃,所以她们开始向谷仓走去。你的工作是要指出哪只母牛会最先到达谷仓(在给出的测试数据中,总会有且只有一只最快的母牛)。在挤奶的时候(晚餐前),每只母牛都在她自己的牧场上,一些牧场上可能没有母牛。每个牧场由一条条道路和一个或多个牧场连接(可能包括自己)。有时,两个牧场(可能是字母相同的)之间会有超过一条道路相连。至

Ciocio 1179
上一篇: USACO section 2.4 Cow Tours(并查集+最短路)
下一篇: USACO section 2.4 Fractions to Decimals(小数处理)
剑不飞
博客等级 码龄15年 86粉丝 505原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值