Loading...

单调栈-大鱼吃小鱼问题

在这里插入图片描述

代码求解

栈是一个n*2的二维数组,每个元素包含两个数,0位置的是体重,1位置的是轮数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
	public static int MAXN = 100001;
	public static int[] arr = new int[MAXN];
	public static int n;
	public static int[][] stack = new int[MAXN][2];
	public static int r;

	public static void main(String[] args)throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StreamTokenizer in = new StreamTokenizer(br);
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

		while(in.nextToken()!=StreamTokenizer.TT_EOF){
			n = (int)in.nval;
			for(int i=0;i<n;i++){
				in.nextToken();
				arr[i]=(int)in.nval;
			}
			out.println(turns());
		}
		out.flush();
		out.close();
		br.close();
	}

	public static int turns(){
		r = 0;
		int ans  = 0;
		for(int i=n-1,curTurns;i>=0;i--){
			curTurns = 0;
			while(r>0&&stack[r-1][0]<arr[i]){
				curTurns = Math.max(curTurns+1, stack[--r][1]);
			}
			stack[r][0]=arr[i];
			stack[r++][1]=curTurns;
			ans = Math.max(ans, curTurns);
		}
		return ans;
	}
Code Road Record