小Q系列故事——电梯里的爱情

来源:互联网 发布:网络音乐地址mp3格式 编辑:程序博客网 时间:2024/04/29 04:34
Problem Description
  细心的同事发现,小Q最近喜欢乘电梯上上下下,究其原因,也许只有小Q自己知道:在电梯里经常可以遇到他心中的女神HR。
  电梯其实是个很暧昧的地方,只有在电梯里,小Q才有勇气如此近距离接近女神,虽然觉得有点不自在,但次数多了,女神也习惯了小Q的存在,甚至熟悉到仿佛不说上句话自己也都觉得不合适了。可是,他们的谈话也仅仅限于今天天气不错啊或是你吃了吗之类的,往往在对方微笑点头后就再次陷入难堪的沉默之中。  于是,小Q便在陪伴女神的同时,也关注着电梯中显示的楼层数字,并且他注意到电梯每向上运行一层需要6秒钟,向下运行一层需要4秒钟,每开门一次需要5秒(如果有人到达才开门),并且每下一个人需要加1秒。
  特别指出,电梯最开始在0层,并且最后必须再回到0层才算一趟任务结束。假设在开始的时候已知电梯内的每个人要去的楼层,你能计算出完成本趟任务需要的总时间吗?
  这是个很简单的问题,要知道,小Q已经修炼到快速心算出结果的境界,现在你来编程试试吧!
 

Input
输入首先包含一个正整数C,表示有C组测试用例。
接下来C行每行包含一组数据,每组数据首先是一个正整数N,表示本次乘坐电梯的人数,然后是N个正整数Ai,分别表示大家要去的楼层。

[Technical Specification]
C<=100
N<=15
Ai<=100
 

Output
请计算并输出完成一趟任务需要的时间,每组数据输出占一行。
 

Sample Input
24 2 4 3 2 3 10 10 10
 

Sample Output
59108
 

Source

2013腾讯编程马拉松初赛第一场(3月21日)

我的代码:

import java.util.Scanner;public class Main {/** * 快速排序的分割算法 *  * @param floor * @param start * @param end * @return */private static int partition(int[] floor, int start, int end) {int i = start - 1;for (int j = start; j < end; j++) {if (floor[j] <= floor[end]) {i += 1;swap(floor, i, j);}}swap(floor, i + 1, end);return (i + 1);}/** * 快速排序 *  * @param floor * @param start * @param end */private static void quick_sort(int[] floor, int start, int end) {if (start < end) {int q = partition(floor, start, end);quick_sort(floor, start, q - 1);quick_sort(floor, q + 1, end);}}private static void swap(int[] floor, int i, int j) {int temp = floor[i];floor[i] = floor[j];floor[j] = temp;}private static void show(int[] floor) {for (int i = 0; i < floor.length; i++) {System.out.printf("%4d", floor[i]);}System.out.println();}/** * 两层之间的耗时(包括同一层的多个人) *  * @param a * @param b * @return */private static int floorTime(int a, int b) {if (a == b)return 1;return ((b - a) * 6 + 5 + 1);}/** * 计算总耗时 *  * @param floor * @return */private static int totalTime(int[] floor) {int time = 0;int before = 0;for (int i = 0; i < floor.length; i++) {time += floorTime(before, floor[i]);before = floor[i];}time += 4 * floor[floor.length - 1];return time;}/** * @param args */public static void main(String[] args) {// TODO 自动生成的方法存根Scanner scanner = new Scanner(System.in);int C = scanner.nextInt();for (int i = 0; i < C; i++) {int num = scanner.nextInt();int[] floor = new int[num];for (int j = 0; j < floor.length; j++) {floor[j] = scanner.nextInt();}quick_sort(floor, 0, floor.length - 1);// show(floor);System.out.println(totalTime(floor));}scanner.close();}}


以上是自己当时写的代码,思路 就是通过排序(快速排序)的方式,算出每一层的耗时。可能方法比较笨拙,如有好的方法欢迎交流~~