首页 > 专题系列 > Java解POJ > POJ 1868 Antiarithmetic? [解题报告] Java
2013
11-10

POJ 1868 Antiarithmetic? [解题报告] Java

Antiarithmetic?

问题描述 :

A permutation of n is a bijective function of the initial n natural numbers: 0, 1, … n-1. A permutation p is called antiarithmetic if there is no subsequence of it forming an arithmetic progression of length bigger than 2, i.e. there are no three indices 0 <= i < j < k < n such that (pi , pj , pk) forms an arithmetic progression.

For example, the sequence (2, 0, 1, 4, 3) is an antiarithmetic permutation of 5. The sequence (0, 5, 4, 3, 1, 2) is not an antiarithmetic permutation as its first, fifth and sixth term (0, 1, 2) form an arithmetic progression; and so do its second, forth and fifth term (5, 3, 1).

Your task is to check whether a given permutation of n is antiarithmetic.

输入:

There are several test cases, followed by a line containing 0. Each test case is a line of the input file containing a natural number 3 <= n <= 10000 followed by a colon and then followed by n distinct numbers separated by whitespace. All n numbers are natural numbers smaller than n.

输出:

For each test case output one line with yes or no stating whether the permutation is antiarithmetic or not.

样例输入:

3: 0 2 1 
5: 2 0 1 3 4
6: 2 4 3 5 0 1
0

样例输出:

yes
no
yes

解题代码:

/* @author: */
import java.util.Scanner;
public class Main {
  private int n;
  private int a[];

  public Main(int n,int[] a){
   this.n=n;
   this.a=a;
 }
  public boolean doIt(){
   for(int j=1;j< n/2;j++)
   {
	for(int i=j;i< n-j;i++)
	{
         if((a[i-j]-a[i])*(a[i+j]-a[i])< 0)
	  {
		return true;
	  }
	}
   }
   return false;
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
	while(sc.hasNext())
	{    
         int n=0;
         String s=sc.next();
         if(s.endsWith(":"))
	      n=Integer.parseInt(s.substring(0,s.length()-1));
         if(n==0) break;
           int a[]=new int[n];
	  for(int i=0;i< n;i++){
	    int tempno=sc.nextInt();
	    a[tempno]=i;
	  }
         Main m=new Main(n,a);
	  if(!m.doIt())
	    System.out.printf("yes\n");
	  else
	    System.out.printf("no\n");
     }
   }
}

  1. “可以发现,树将是满二叉树,”这句话不对吧,构造的树应该是“完全二叉树”,而非“满二叉树”。