首页 > 试题广场 >

Elevator (20)

[编程题]Elevator (20)
  • 热度指数:2077 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
The highest building in our city has only one elevator. A request list is made up with N positive numbers. The numbers denote at which floors the elevator will stop, in specified order. It costs 6 seconds to move the elevator up one floor, and 4 seconds to move down one floor. The elevator will stay for 5 seconds at each stop.
For a given request list, you are to compute the total time spent to fulfill the requests on the list. The elevator is on the 0th floor at the beginning and does not have to return to the ground floor when the requests are fulfilled.

输入描述:
Each input file contains one test case. Each case contains a positive integer N, followed by N positive numbers. All the numbers in the input are less than 100.


输出描述:
For each test case, print the total time on a single line.
示例1

输入

3 2 3 1

输出

41
推荐
本题是模拟类型
用fromFloor记录当前所在楼层,toFloor记录要达到的楼层。
如果toFloor < fromFloor,花费的时间为(fromFloor - toFloor)*4+5。
如果toFloor >= fromFloor,花费的时间为(toFloor - fromFloor)*6+5。

代码如下:
import java.io.PrintStream;
import java.util.Scanner;

public class Main {
	public static Scanner in = new Scanner(System.in);
	public static PrintStream out = System.out;

	public static void main(String[] args) {
		int n = in.nextInt();
		int time = 0;
		int toFloor,fromFloor = 0;
		
		for(int i=0;i<n;++i){
			toFloor = in.nextInt();
			time += moveElevator(fromFloor,toFloor);
			
			fromFloor = toFloor;
		}
		out.println(time);
	}

	// 从fromFloor到toFloor花费的时间
	private static int moveElevator(int fromFloor, int toFloor) {
		if(toFloor<fromFloor){
			return (fromFloor-toFloor)*4+5;
		}
		return (toFloor-fromFloor)*6 + 5;
	}
}

编辑于 2015-08-18 23:00:15 回复(0)

问题信息

难度:
0条回答 5634浏览

热门推荐

通过挑战的用户

Elevator (20)