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.

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

思考

这里面c++的解法用到了头文件algorithm

纯C语言可以使用algorithm头文件,因为algorithm是C++库里的 algorithm中的大部分算法都是针对C++语言特有的,需要用到STL(标准模板库)的容器等。具体可以参考:https://en.wikipedia.org/wiki/Algorithm_(C%2B%2B) 纯C语言可以在网上找一些第三方的库去替代,但是灵活性肯定是比C++的标准库提供的方法低很多,因为语言本身的局限性。

交换和求较小值

/*交换两个整数值*/
myswap(int *a,int *b){
int *temp;
temp=a;
a=b;
b=temp;
}//这个交换对外界的那两个left与right没有影响
/*交换修正版*/
myswap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}/*传入指针,就能修改这个值本身*/
/*求两整数较小值*/
int mymin(int a,int b){
return (a>b)?b:a;
}

AC代码

#include <stdio.h>
#define max 100005
int dis[max], A[max];
/*交换两个整数值*/
myswap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}//还是有疑惑的
/*求两整数较小值*/
int mymin(int a,int b){
return a>b?b:a;
}
int main() {
int sum = 0, query, n, left, right;
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%d", &A[i]);
sum += A[i];
dis[i] = sum;//存入了顺时针从1号点到i+1号点的距离
}
scanf("%d", &query);
for(int i = 0; i < query; i++) {
scanf("%d%d", &left, &right);
if(left > right) myswap(&left, &right);
int temp = dis[right - 1] - dis[left - 1];
printf("%d\n", mymin(temp, sum - temp));
}
return 0;
}

最新文章

  1. JAVA抽象方法,接口
  2. NBUT 1457 Sona(莫队算法+离散化)
  3. ruby中的reject和reject!
  4. 保障视频4G传输的流畅性,海康威视摄像头相关设置
  5. 老韩思考:一个卖豆腐的能转行IT吗? 你的卖点在哪里?
  6. Delphi中的GetEnumName和GetEnumValue的使用方法
  7. Runtime.exec()
  8. .Net Standard扩展支持实例分享
  9. jar包后台启动--nohup篇
  10. 解读Raft(一 算法基础)
  11. c/c++ 多线程 等待一次性事件 异常处理
  12. 【Python 15】分形树绘制3.0(递归函数)
  13. Kong(V1.0.2) Securing the Admin API
  14. Websocket通信过程
  15. [Python设计模式] 第8章 学习雷锋好榜样——工厂方法模式
  16. ArrayList与List性能测试
  17. Java时间操作常用api
  18. session会话时间
  19. B/S网络概述
  20. mysql批量insert速度超慢

热门文章

  1. SpringBoot | 第二十四章:日志管理之AOP统一日志
  2. Xcode警告忽略
  3. 消除transition闪屏
  4. python全栈测试题(一)
  5. [转]linux远程登入不需要密码
  6. 调用cmd命令行命令(借鉴)
  7. jmeter之吞吐量、吞吐率、TPS、带宽及压力测试和负载测试及其区别
  8. 修复SQL中的孤立账户
  9. cms-幻灯片的实现
  10. ubuntu 16.4 安装配置IK6.3.2