1046 Shortest Distance
来源:互联网 发布:闪电分期淘宝上怎么扫 编辑:程序博客网 时间:2024/05/17 06:16
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 9
3
1 3
2 5
4 1
Sample Output:
3
10
7
解题思路:如果只是简单的记录各个点之间的距离,每次询问的时候进行计算的话,最后一个测试点会运行超时,于是就改成数组中记录的是,从一号点到当前点的总距离,查询的时候直接将距离相减就是正向的两个点之间的距离,反向的距离用总的环的距离减去正向两个点之间的距离就可,输出较小的距离。
#include<iostream>#include<vector>#include<stdio.h>using namespace std;int main(){ for (int n; scanf("%d", &n) != EOF;){ int *arr = new int[n+1]; int total = 0; for (int i = 1; i <= n; i++){ arr[i] = total; int temp; scanf("%d", &temp); total += temp; } int m; scanf("%d", &m); while (m--){ int begin; int end; scanf("%d%d", &begin, &end); if (begin > end){ begin = begin^end; end = begin^end; begin = begin^end; } int distance = arr[end] - arr[begin]; if (distance > total - distance){ printf("%d\n", total - distance); } else{ printf("%d\n", distance); } } }}
- pat 1046 Shortest Distance
- PAT 1046 Shortest Distance
- 1046 Shortest Distance
- 浙大PAT 1046题 1046. Shortest Distance
- Pat(Advanced Level)Practice--1046(Shortest Distance)
- 1046. Shortest Distance
- 1046. Shortest Distance (20)
- 1046. Shortest Distance
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- PAT 1046. Shortest Distance
- PAT 1046. Shortest Distance
- 1046. Shortest Distance
- 1046. Shortest Distance
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- Android DownloadManager 的使用
- STL中string的基本用法范例
- 泛型type体系与反射
- ubuntu下安装rpm文件
- 多线程socket编程--聊天程序
- 1046 Shortest Distance
- 计算机验证
- 阿里云服务器Web项目配置发布全过程(三)
- Test...
- 高并发程序设计入门
- POJ 3087
- Android即时通讯--仿QQ即时聊天:(三)核心代码抽取与登录逻辑
- MySQL详解--锁
- 解决dubbox-demo-provider.xml报错的问题:提示Failed to read schema document