首页 > 专题系列 > Java解POJ > POJ 1354 Placement of Keys [解题报告] Java
2013
11-09

POJ 1354 Placement of Keys [解题报告] Java

Placement of Keys

问题描述 :

Assume that there are n (3<=n<=200) boxes identified by A1, A2,..., An , and each box Ai is configured a lock which is different from the others. Now put n keys to the n locks into the n boxes, each box can only hold a key. After locking all the boxes, unclench the boxes named A1, A2 and fetch out the keys in them to unlock the locked boxes. If the two keys can open some box, fetch out the key in the box to unlock other locked boxes again. If we can open all the boxes finally, we call the placement of the n keys good placement. How many are there different good placements of the n keys?

输入:

The input file, ending with -1, contains several data, each of which holds a line.

输出:

According to every input datum, compute the number of different good placements. Each output data hold two lines, the first line is held by the input datum, followed by a colon, which follows an equal mark before which is an N; the second is held by the number of different good placement of the n keys.

样例输入:

6
8
-1

样例输出:

N=6:
240
N=8:
10080

解题代码:

import java.io.BufferedInputStream;   
import java.math.BigDecimal;   
import java.util.Scanner;   
public class Main {   
  
    public static void main(String[] args) {   
        Scanner scan = new Scanner(new BufferedInputStream(System.in));   
        while (scan.hasNext()) {   
            int n = scan.nextInt();   
            if (n == -1) {   
                break;   
            }   
            BigDecimal nn = new BigDecimal(n);   
            BigDecimal sum = BigDecimal.ONE;   
            for (BigDecimal i = BigDecimal.ONE; i.compareTo(nn) == -1; i = i.add(BigDecimal.ONE)) {   
                sum = sum.multiply(i);   
            }   
            System.out.println("N=" + n + ":");   
            System.out.println(sum.multiply(new BigDecimal(2)));   
        }   
    }   
}

  1. 第二个方法挺不错。NewHead代表新的头节点,通过递归找到最后一个节点之后,就把这个节点赋给NewHead,然后一直返回返回,中途这个值是没有变化的,一边返回一边把相应的指针方向颠倒,最后结束时返回新的头节点到主函数。