火车站的列车调度铁轨的结构如下图所示。
两端分别是一条入口(Entrance)轨道和一条出口(Exit)轨道,它们之间有N条平行的轨道。每趟列车从入口可以选择任意一条轨道进入,最后从出口离开。在图中有9趟列车,在入口处按照{8,4,2,5,3,9,1,6,7}的顺序排队等待进入。如果要求它们必须按序号递减的顺序从出口离开,则至少需要多少条平行铁轨用于调度?
输入格式:
输入第一行给出一个整数N (2 ≤ N ≤10
5
),下一行给出从1到N的整数序号的一个重排列。数字间以空格分隔。
输出格式:
在一行中输出可以将输入的列车按序号递减的顺序调离所需要的最少的铁轨条数。
输入样例:
9
8 4 2 5 3 9 1 6 7
输出样例:
4
超时代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
//** Class for buffered reading int and double values *//*
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
// ** call this method to initialize reader for InputStream *//*
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
// ** get next word *//*
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static boolean hasNext()throws IOException {
return tokenizer.hasMoreTokens();
}
static String nextLine() throws IOException{
return reader.readLine();
}
static char nextChar() throws IOException{
return next().charAt(0);
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static float nextFloat() throws IOException {
return Float.parseFloat(next());
}
}
public class Main {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
int []rail = new int[n];
int len=0;
for (int i = 0; i < n; i++) {
int x = Reader.nextInt();
if (len==0||rail[len-1]<x) {
rail[len++] = x;
}else {
int l = 0;
int r = len-1;
while(l<r) {
int mid = (l+r)>>1;
if (rail[mid]>x) {
r = mid;
}else {
l = mid+1;
}
}
rail[l] = x;
}
}
System.out.println(len);
}
}