poj 3250 Bad Hair Day

以前总是靠人肉暴力模拟,这个题目复杂度太高搞不过去了,

栈模拟,又学到了新的东西

import java.io.*;
import java.math.BigInteger;
import java.util.*;
class item1{
	int value,idx;
	public item1(int x,int y){
		value=x;idx=y;
	}
}

class problem{
    int n,t=0;
    long sum;
    item1 stack[];
    void solver() throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));        
        n = Integer.valueOf(reader.readLine());
        stack = new item1[n+1];
        stack[t]=new item1(Integer.MAX_VALUE,0);
        for(int i=1;i<=n+1;i++){
        	int tmp;
        	if(i=stack[t].value&&t>=1) {        		
        		sum+=i-1-stack[t--].idx;
        	}
        	stack[++t]=new item1(tmp,i);
        }
        System.out.println(sum);
    }
}
public class Main{
    public static void main (String [] args) throws Exception {
        problem p = new problem();
        p.solver();
    }
}


 

你可能感兴趣的:(POJ)