PAT 1046 Shortest Distance 翻译 分析 代码

28 篇文章 0 订阅
27 篇文章 0 订阅
题目:1046 Shortest Distance (20)(20 分)【最短路径】

The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.

【案例很简单:在一条路径上给出N个出口,共同组成一个圆形,你要给出任意一对路径上面的最短距离】

Input Specification:

Each input file contains one test case. For each case, the first line contains an integer N (in [3, 10^5^]), followed by N integer distances D~1~ D~2~ ... D~N~, where D~i~ is the distance between the i-th and the (i+1)-st exits, and D~N~ is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (<=10^4^), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 10^7^.


【每个输入的文档都包含一个测试案例。对每个案例来说,第一行要包括一个整数N(N在3与10的五次方之间),输入N个数据,用以表示距离D1,D2……Dn,Di是点i与点i+1之间的距离,Dn是点N与点1的距离。所有在同一行的数据都要用“ ”隔开。在第二段给出一个正数M(M<=10^4),下面输出M行,每行都要包括一对数据,用以提供从1到N之间任意的距离,最后要保证总的距离之和不多于10^7】

Output Specification:

For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.

【对每个测试数据,在M行里面输出你的结果,每个结果都要符合所给出的数据的最短路径】


【注】:以下分析所在为代码注释,通过注释可以分析得到此题答案。

【注】:此代码是由Dev c++ 5.11 所写,运用c++语言。  其他方法后续会另写博客给出方式。惊讶

/**************************************************************************************************************************/

#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int ACW=100005;                                            //M<=10^5,使数组大于操作次数 ; 
int K,left,right,inquiry,sum=0,S[ACW],dis[ACW],i;
scanf("%d",&K);
for(i=1;i<=K;i++)
{
scanf("%d",&S[i]);                                    //输入每段的路程分别是; 
sum+=S[i];	                                //当i不为K时,是中间变量,把数据传给dis[i],当i为K时,是总路程的加和; 
dis[i]=sum;	                        //dis[i]是由点1到点i的距离; 
}
/************查询段************/
scanf("%d",&inquiry); 
for(i=1;i<=inquiry;i++)
{
scanf("%d%d",&left,&right);
if(left>right)	                         //规定一个特定的路径顺序,例如顺时针,输入查询时,使左查询点和右查询点产生大小次序; 
{    
swap(left,right);                                //使左点小于右点; 
}
int temp= dis[right-1]-dis[left-1];            //通过运算获得两点之间的距离差距; 
printf("%d\n",min(temp,sum-temp)) ;    //比较总路程与顺序查询路径的差值和顺序查询的大小,输出最近的距离; 
}


return 0;
 } 

/*************************************************************************************************************************/

【注意】本程序运用的是C++,在其中用algorith头文件, 通过使用using namespace std ,调用了其中的swap函数和min函数。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值