南大高级算法作业之备考题——时间分隔

题意:给出火车进出站时间,求出站台能同时容纳几辆火车才能满足需要。

题解:对进出站时间进行排序,数组里存放的是下标,进站时间下标依次为0,1,2...n-1出站时间下标为n,n+1,n+2...2n-1,最后沿着排好的序,遇到进站的坐标就+1,遇到出站的就-1,得到最大的值即可。 

import java.util.*;
public class Main {
    public static void main(String[] args) {
    	Scanner scan = new Scanner(System.in);
		int e_num = scan.nextInt();//测试数
		while(e_num>0){
			int tcount = scan.nextInt();//the num of train
			int[] time = new int[tcount*2];
			int[] position = new int[tcount*2];//store position
			for(int i=0;i<tcount*2;i++){	
				time[i] = scan.nextInt();	
			}
			for(int i=0;i<tcount*2;i++){	
				position[i] = i;	
			}
			//sort
			for(int i=0;i<tcount*2;i++){
				int min = time[position[i]];
				int pos = i;
				for(int j=i;j<tcount*2;j++){
					if(min > time[position[j]]){
						min = time[position[j]];
						pos = j;
					}
				}
				int temp = position[pos];
				position[pos] = position[i];
				position[i] = temp;	
			}	
			int result = 0;
			int temp = 0;
			for(int i=0;i<tcount*2;i++){
				if(position[i]<tcount){
					temp ++;	
				}else{
					temp --;
				}
				result = Math.max(result, temp);	
			}
			System.out.println(result);
			e_num --;
		}
    }
}
发布了36 篇原创文章 · 获赞 2 · 访问量 1977

猜你喜欢

转载自blog.csdn.net/fumonster/article/details/103291338