PAT 甲级 1046.Shortest Distance C++/Java
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PAT 甲级 1046.Shortest Distance C++/Java,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2172字,纯文字阅读大概需要4分钟。
内容图文
![PAT 甲级 1046.Shortest Distance C++/Java](/upload/InfoBanner/zyjiaocheng/643/68d4f85f2db44f8e84aa303f57a1665c.jpg)
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]), followed by N integer distances D?1?? D?2?? ? D?N??, where D?i?? is the distance between the i-th and the (-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 (≤), 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 1.
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
题目大意:
输入一个N:表示有N个出口
输入N个数:D1,D2,....DN,表示第 i 个 与 第 i + 1 个出口之间的距离
输入一个M:表示有M组数据
剩下M行,每行输入2个数 i 和 j:表示 i 与 j 之间的最短距离
分析:
Dn[i] :保存第 i 个与第 i + 1 个出口之间的距离
sum :保存总距离(从1到N再到1,形成的一个环)
给出的两个出口: exit1, exit2 ,计算 两个出口之间的距离 s ,再与 sum - s 比较,最小的那个就是最短距离
一开始想着用累加的方式,用D1,D2,DN计算出口之间的距离,但是这样会超时
所以需要对距离进行预处理,得到一个 数组 disc
里面保存了从 1 到 2, 从 1 到 3, 从 1 到 4 的距离
如果要计算从 2 到 4 的距离, 就相当于是 1到4的距离 - 1到2的距离
需要注意的是:第一个出口必须小于第二个出口,否则就交换两个值
C++实现:
#include <iostream> #include <vector> using namespace std; int main() { int N; cin >> N; vector<int> Dn(N + 1); vector<int> disc(N + 1); int sum = 0; for (int i = 1; i <= N; ++i) { cin >> Dn[i]; sum += Dn[i]; disc[i] = sum; } int M; int exit1 = 0, exit2 = 0; cin >> M; for (int i = 0; i < M; ++i) { cin >> exit1 >> exit2; if (exit1 > exit2) { swap(exit1, exit2); } int shortest = 0; int temp = disc[exit2 - 1] - disc[exit1 - 1]; shortest = temp < sum - temp ? temp : sum - temp; cout << shortest << endl; } return 0; }
Java实现:
内容总结
以上是互联网集市为您收集整理的PAT 甲级 1046.Shortest Distance C++/Java全部内容,希望文章能够帮你解决PAT 甲级 1046.Shortest Distance C++/Java所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。