civ3

编程好玩

导航

钻井布局-第一题

基于对象的简单递归算法(用Java实现)。问题描述见http://mcm.edu.cn/mcm99/mcm99problems.htm
面向对象的程序更贴近自然语言描述。

Java内置对象HashSet更贴近数学中抽象集合的概念,它不关注元素的类型,这有点像指针数组,但是用C++实现起来程序的可读性就要差很多……

import java.util.*;
public class HelloWorld{
    public static void main(String args[]){
  P.collection=new HashSet();
  P.epl=0.05;
  new P(0.50,2.00);//1
  new P(1.41,3.50);//2
  new P(3.00,1.50);//3
  new P(3.37,3.51);//4
  new P(3.40,5.50);//5
  new P(4.72,2.00);//6
  new P(4.72,6.24);//7
  new P(5.43,4.10);//8
  new P(7.57,2.01);//9
  new P(8.38,4.50);//10
  new P(8.98,3.41);//11
  new P(9.50,0.80);//12
  //
  SP.collection=new HashSet();
  SP.bPath=new HashSet();
  new SP();
  System.out.println(SP.bPath);
  System.out.println(SP.bPath.size());
    }
}

class SP extends HashSet{
 static HashSet collection;
 static HashSet bPath;
// HashSet hasBeen;
 HashSet hasNotBeen;
 SP(){
  super();
  this.hasNotBeen=new HashSet(P.collection);
  this.search();
 }
 SP(SP sp,P p){
  //dupilicate
  this.addAll(sp);
  this.add(p);
  //not
  this.hasNotBeen=new HashSet(P.collection);
  this.hasNotBeen.removeAll(this);
  
  //
  if(!SP.collection.contains(this)){
   //collect it
   SP.collection.add(this);
   //searcH
   this.search();
   if(this.size()>SP.bPath.size())
    SP.bPath=this;
  }
  
 }
 
 void search(){
  //recurrent
  for(Iterator it = this.hasNotBeen.iterator(); it.hasNext();){
   P p2=(P)it.next();
   boolean flag=true;
   for(Iterator me =this.iterator();me.hasNext();){
    if(!((P)me.next()).isNearTo(p2)){
     flag=false;
     break;
    }
   }
   if(flag)new SP(this,p2);
  }
 }
}

class P{
 int index;
 double ox,oy,x,y;
 static double epl;
 static HashSet collection;
 P(double x,double y){
  this.index=1+P.collection.size();
  this.ox=x;
  this.oy=y;
  this.x=x-Math.floor(x);
  this.y=y-Math.floor(y);
  P.collection.add(this);
 }
 boolean isNearTo(P p){
  return Math.max(Math.abs(this.x-p.x),Math.abs(this.y-p.y))<=P.epl;
 }
 public String toString(){
  return this.index+":["+this.ox+","+this.oy+"]";
 }
}

求解结果:

[5:[3.4,5.5], 2:[1.41,3.5], 10:[8.38,4.5], 4:[3.37,3.51]]
4

posted on 2005-10-15 17:14  civ3's .NET studying  阅读(1029)  评论(0编辑  收藏  举报