1046. Shortest Distance (20)
来源:互联网 发布:书旗小说阅读软件 编辑:程序博客网 时间:2024/06/04 18:02
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.
Input Specification:
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.
Output Specification:
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
Sample Input:5 1 2 4 14 931 32 54 1Sample Output:
3107
分析:
(1)给定一个长为s环求环中两点的最短距离,其实就是一段距离d和s-d的小值。
(2)求d如果用循环,会超时。所以要在第一次输入循环时候,直接计算出一点到初始点的距离,之后求某两点距离直接相减可得。O(N2)不靠谱啊啊。
#include <stdio.h>int main (){int n,m,i ,circleDistance=0;int dt[100002],dt2[100002],op[10002];scanf("%d",&n);int temp1=0;dt2[0]=0;for (i=0;i<n;i++){scanf("%d",&dt[i]);dt2[i+1]=temp1+dt[i];temp1=dt2[i+1];circleDistance+=dt[i];} scanf ("%d",&m);for (i=0;i<m;i++){int a,b;scanf ("%d%d",&a,&b);if (a>b){int temp=a;a=b;b=temp;}int sd1,sd2;sd1=dt2[b-1]-dt2[a-1];sd2=circleDistance-sd1;op[i]=sd1<sd2?sd1:sd2;}for (i=0;i<m;i++){printf ("%d\n",op[i]);}return 0;}
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- hdu 4907 Task schedule(水题)
- Best Time to Buy and Sell Stock III
- Android异常问题分析
- Android支持的媒体格式
- linux 中JDK环境变量不一致问题导致mysql无法连接,总是告诉权限出错
- 1046. Shortest Distance (20)
- 深度学习:未来机器人的进化途径
- zoj 1109 Language of FatMouse (字典树Trie)
- 爆笑:GIF 动画展示开发者的生活
- hdu 1160 FatMouse's Speed
- hdu 2674 N!Again(找规律)
- hdu-2709-Sumsets
- iOS 动画实现和理解
- openFileOutput 文件属性设置、主动配置文件的可读写属性及其实现方式