首页 > 专题系列 > Java解POJ > POJ 2796 Feel Good [解题报告] Java
2013
11-12

POJ 2796 Feel Good [解题报告] Java

Feel Good

问题描述 :

Bill is developing a new mathematical theory for human emotions. His recent investigations are dedicated to studying how good or bad days influent people’s memories about some period of life.

A new idea Bill has recently developed assigns a non-negative integer value to each day of human life.

Bill calls this value the emotional value of the day. The greater the emotional value is, the better the daywas. Bill suggests that the value of some period of human life is proportional to the sum of the emotional values of the days in the given period, multiplied by the smallest emotional value of the day in it. This schema reflects that good on average period can be greatly spoiled by one very bad day.

Now Bill is planning to investigate his own life and find the period of his life that had the greatest value. Help him to do so.

输入:

The first line of the input contains n – the number of days of Bill’s life he is planning to investigate(1 <= n <= 100 000). The rest of the file contains n integer numbers a1, a2, ... an ranging from 0 to 106 – the emotional values of the days. Numbers are separated by spaces and/or line breaks.

输出:

Print the greatest value of some period of Bill’s life in the first line. And on the second line print two numbers l and r such that the period from l-th to r-th day of Bill’s life(inclusive) has the greatest possible value. If there are multiple periods with the greatest possible value,then print any one of them.

样例输入:

6
3 1 6 4 5 2

样例输出:

60
3 5

解题代码:

//* @author: [email protected]
import java.io.*;
public class Main
{
 static int[] b,c;
 static long[] e,d,p;
 public static void main(String[] args)throws IOException
 {
	InputStreamReader is=new InputStreamReader(System.in);
	BufferedReader in=new BufferedReader(is);
	int a=Integer.parseInt(in.readLine());
	p=new long[a+2];
	b=new int[a+1];
	c=new int[a+1];
	d=new long[a+1];
	e=new long[a+1];
	String[] ss=in.readLine().split(" ");
	for(int i=1;i<=a;i++)
		e[i]=d[i]=p[i]=Long.parseLong(ss[i-1]);
	p[0]=p[a+1]=-1;
	long max=-1;
	for(int i=1;i<=a;i++)
	{
         b[i]=1;
	  int j=i;
	  while(p[j-b[j]]>=p[i])
	  {
		j-=b[j];
		b[i]+=b[j];
		d[i]+=d[j];
	   }
	}
	for(int i=a;i>0;i--)
	{
	  c[i]=1;
	  int j=i;
	  while(p[j+c[j]]>=p[i])
	  {
	    j+=c[j];
	    c[i]+=c[j];
	    e[i]+=e[j];
	   }
	}
	int st=-1,ed=-1;
	for(int i=1;i<=a;i++)
	{
	   long sum=d[i]+e[i]-p[i];
	   sum*=p[i];
	   if(sum>max)
	   {
		max=sum;
		st=i-b[i]+1;
		ed=i+c[i]-1;
	   }
	 }
	
	System.out.println(max);
	System.out.println(st+" "+ed);
   }
}

  1. 嗯 分析得很到位,确实用模板编程能让面试官对你的印象更好。在设置辅助栈的时候可以这样:push时,比较要push的elem和辅助栈的栈顶,elem<=min.top(),则min.push(elem).否则只要push(elem)就好。在pop的时候,比较stack.top()与min.top(),if(stack.top()<=min.top()),则{stack.pop();min.pop();},否则{stack.pop();}.