问题 E: Shortest Distance (20)
时间限制: 1 Sec 内存限制: 32 MB
提交: 1478 解决: 485
[提交][状态][讨论版][命题人:外部导入]
题目描述
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.
输入
Each input file contains one test case. For each case, the first line contains an integer N (in [3, 105]), followed by N integer distances D1 D2 … DN, where Di is the distance between the i-th and the (i+1)-st exits, and DN 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 (<=104), 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 107.
输出
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
样例输入
5 1 2 4 14 9
3
1 3
2 5
4 1
样例输出
3
10
7
我写的代码比较麻烦,算法很简单,求所有路径的和sum,然后比较两个节点之间的路径长度tmp以及sum-tmp的大小,取小的;
算法书上面的算法比我写的要优化很多,计算出从第一个结点到之后每一个节点的长度dis[i],然后根据输入的结点l,r,用dis[i]-dis[r]就欧克了。
两个代码都在下面。
#include <stdio.h>
#include <algorithm>
using namespace std;
#define max 100010
int main()
{
int n=0,i=0,m=0,sum=0;//m组数据,sum总长
int a[max]={0},rcd[max]={0};//输入的路径长度和每组最短长度
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
sum+=a[i];
}
int l=0,r=0;
scanf("%d",&m);
for(i=0;i<m;i++){
int tmp=0,j=0;
// int min=0;
scanf("%d %d",&l,&r);
if(l>r) swap(l,r);//可以用swap函数代替下面两段注释掉的代码
for(j=l-1;j<=r-2;j++){
tmp+=a[j];
}
rcd[i]=min(tmp,sum-tmp);//用min函数代替用来比较的代码
/*
if(r>l){
for(j=l-1;j<=r-2;j++){
tmp+=a[j];
}
}
else if(l>r){
for(j=r-1;j<=l-2;j++){
tmp+=a[j];
}
}
min=sum-tmp;
if(tmp<min) rcd[i]=tmp;
else if(tmp>min) rcd[i]=min;
*/
}
for(i=0;i<m;i++){
printf("%d\n",rcd[i]);
}
return 0;
}
#include <stdio.h>
#include <algorithm>
using namespace std;
#define max 100010
int main()
{
int a[max]={0},dis[max]={0};
int sum=0,i=0,n=0,m=0;
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
sum+=a[i];
dis[i]=sum;
}
int l=0,r=0;
scanf("%d",&m);
for(i=0;i<m;i++){
scanf("%d %d",&l,&r);
if(l>r) swap(l,r);
int tmp=dis[r-1]-dis[l-1];
printf("%d\n",min(tmp,sum-tmp));
}
return 0;
}