1. 程式人生 > >【POJ 2409】Let it Bead(Polay 定理)

【POJ 2409】Let it Bead(Polay 定理)

Let it Bead
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 5389 Accepted: 3603

Description

"Let it Bead" company is located upstairs at 700 Cannery Row in Monterey, CA. As you can deduce from the company name, their business is beads. Their PR department found out that customers are interested in buying colored bracelets. However, over 90 percent of the target audience insists that the bracelets be unique. (Just imagine what happened if two women showed up at the same party wearing identical bracelets!) It's a good thing that bracelets can have different lengths and need not be made of beads of one color. Help the boss estimating maximum profit by calculating how many different bracelets can be produced. 

A bracelet is a ring-like sequence of s beads each of which can have one of c distinct colors. The ring is closed, i.e. has no beginning or end, and has no direction. Assume an unlimited supply of beads of each color. For different values of s and c, calculate the number of different bracelets that can be made.

Input

Every line of the input file defines a test case and contains two integers: the number of available colors c followed by the length of the bracelets s. Input is terminated by c=s=0. Otherwise, both are positive, and, due to technical difficulties in the bracelet-fabrication-machine, cs<=32, i.e. their product does not exceed 32.

Output

For each test case output on a single line the number of unique bracelets. The figure below shows the 8 different bracelets that can be made with 2 colors and 5 beads.

Sample Input

1 1
2 1
2 2
5 1
2 5
2 6
6 2
0 0

Sample Output

1
2
3
5
8
13
21

Source

[題意][給定一個手鐲,給定m個珠子,n種顏色,詢問有多少種不同的構成方式]

【題解】【Polya 定理】

【和POJ 1286基本一致,只是顏色種數也是變化的】

#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
int n,m;
ll ans,p[1010];

ll gcd(int a,int b)
{
	if(!(a%b)) return b;
	return gcd(b,a%b);
}

int main()
{
	int i,j;
	while(scanf("%d%d",&n,&m)==2&&n&&m)
	 {
	 	memset(p,0,sizeof(p));
	    p[0]=1; ans=0;
	 	for(i=0;i<m;++i) p[i+1]=p[i]*n;
	 	if(m&1) ans=m*p[m/2+1];
	 	 else ans=(m/2)*(p[m/2+1]+p[m/2]);
	 	for(i=1;i<=m;++i) ans+=p[gcd(i,m)];
	 	ans/=2*m;
	 	printf("%I64d\n",ans);
	 }
}