首页 > 专题系列 > Java解POJ > POJ 1286 Necklace of Beads [解题报告] Java
2013
11-09

POJ 1286 Necklace of Beads [解题报告] Java

Necklace of Beads

问题描述 :

Beads of red, blue or green colors are connected together into a circular necklace of n beads ( n < 24 ). If the repetitions that are produced by rotation around the center of the circular necklace or reflection to the axis of symmetry are all neglected, how many different forms of the necklace are there?

输入:

The input has several lines, and each line contains the input data n.

-1 denotes the end of the input file.

输出:

The output should contain the output data: Number of different forms, in each line correspondent to the input data.

样例输入:

4
5
-1

样例输出:

21
39

解题代码:

//* @author: 
import java.util.Scanner;
public class Main{
   public static int gcd(int a,int b){
      return (b!=0) ? gcd(b,a%b):a;
   }

   public static void main(String args[]){
      Scanner in=new Scanner(System.in);
      
      while(true){
          int c=3;
          int s=in.nextInt();
          if(s==-1) break;
          if(s==0){
	    System.out.printf("0\n");
	    continue;
	   }
	   long p[]=new long[64];
            p[0] = 1; // power of c
	   for (int k=0 ; k< s ; k++) 
             p[k+1] = p[k] * c;
	   long  count = ((s&1)!=0) ? s * p[s/2 + 1] : (s/2) * (p[s/2] + p[s/2 + 1]);
		// rotation part
	   for (int k=1 ; k<=s ; k++) 
             count += p[gcd(k, s)];
	   count /= 2 * s;
	   System.out.printf("%d\n",count);
	}
     }
}

  1. I like your publish. It is great to see you verbalize from the coronary heart and clarity on this essential subject matter can be easily noticed.