Java集合之Stack

Stack

  • 定义
C++:stack 
Java:Stack(线程安全) 
  • 创建与其基本操作
创建:
Stack<Integer> stack=new Stack<Integer>
数组:
Stack<Integer> stack[]=new Stack[N]
基本操作:
1	boolean empty() 测试堆栈是否为空。
2	Object peek( ) 查看堆栈顶部的对象,但不移除。
3	Object pop( ) 移除堆栈顶部的对象,并返回该对象。
4	Object push(Object element)
5	int search(Object element) 返回对象在堆栈中的位置,以 1 为基数。
import java.util.*;
import java.io.*;
public class Main {
	   static final int N=(int)1e5+5;
       public static void main(String args[]){
    	   Stack<Integer> stack=new Stack<Integer>();
    	   int a[]= new int[N];
    	   int b[]= new int[N];
    	   Scanner sc=new Scanner(new InputStreamReader(System.in));
    	   while(sc.hasNext()) {
    		   while(!stack.empty()) stack.pop();
    		   int n=sc.nextInt();
    		   if(n==0) break;
    		   for(int i=0;i<n;i++) a[i]=sc.nextInt();
    		   for(int i=0;i<n;i++) {
                    while(!stack.empty()&&a[stack.peek()]>=a[i]) {
                    	stack.pop();
                    }
                    if(stack.empty()) b[i]=-1;
                    else b[i]=stack.peek();
                    stack.push(i);
    		   }
    		   while(!stack.empty()) stack.pop();
    		   long ans=0;
    		   for(int i=n-1;i>=0;i--) {
                   while(!stack.empty()&&a[stack.peek()]>=a[i]) {
                   	   stack.pop();
                   }
                   if(stack.empty()) {
                	   ans=Math.max(ans, (long)a[i]*(n-b[i]-1));
                   }
                   else ans=Math.max(ans, (long)a[i]*(stack.peek()-b[i]-1));
                   stack.push(i);
   		        }
    		    PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
    		    out.println(ans);out.flush();
    	   }
       }
}
  1. MaxTree构造
    链接:http://www.cnblogs.com/zsyacm666666/p/7373904.html
原文地址:https://www.cnblogs.com/zsyacm666666/p/7656100.html