1008 Elevator (20 分) Java实现
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.
Input Specification:
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.
Output Specification:
For each test case, print the total time on a single line.
Sample Input:
3 2 3 1
Sample Output:
41
题目大意:坐电梯,电梯从第0层开始,每上升一层耗时6s,下降一层耗时4s,每一站停5秒,需要求出总共消耗的时间。
解题思路:a[i]表示将要去的层,a[i-1]是当前层,循环i从1开始。楼层上升,则 时间=(将要去的层-当前层)*6+5;楼层下降,则 时间=(当前层-将要去的层)*4+5;特殊情况,电梯不动,时间需要+5s。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s[]=br.readLine().split(" ");
int a[]=new int [s.length];
int n=Integer.parseInt(s[0]);
int time=0;
for(int i=1;i<=n;i++){
a[i]=Integer.parseInt(s[i]);
if(a[i]>a[i-1]){
time+=6*(a[i]-a[i-1])+5;
}else if(a[i]<a[i-1]){
time+=4*(a[i-1]-a[i])+5;
}else if(a[i]==a[i-1]){
time+=5;
}
}
System.out.println(time);
}
}