hdu 1817 Necklace of Beads (polya)

Necklace of Beads

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1049    Accepted Submission(s): 378


Problem Description
Beads of red, blue or green colors are connected together into a circular necklace of n beads ( n < 40 ). 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?

 
Input
The input has several lines, and each line contains the input data n.
-1 denotes the end of the input file.

 
Output
The output should contain the output data: Number of different forms, in each line correspondent to the input data.
 
Sample Input
4
5
-1
 
Sample Output
21
39

help

C/C++:

 1 #include <map>
 2 #include <queue>
 3 #include <cmath>
 4 #include <vector>
 5 #include <string>
 6 #include <cstdio>
 7 #include <cstring>
 8 #include <climits>
 9 #include <iostream>
10 #include <algorithm>
11 #define INF 0x3f3f3f3f
12 #define LL long long
13 using namespace std;
14 const int MAX = 1e5 + 10;
15 
16 __int64 sum, n;
17 
18 __int64 gcd(__int64 a, __int64 b)
19 {
20     if (b == 0) return a;
21     return gcd(b, a%b);
22 }
23 
24 __int64 my_pow(__int64 a, __int64 m)
25 {
26     __int64 ans = 1;
27     while (m)
28     {
29         if (m & 1) ans *= a;
30         a *= a;
31         m >>= 1;
32     }
33     return ans;
34 }
35 
36 int main()
37 {
38     while (scanf("%I64d", &n), n != -1)
39     {
40         sum = 0;
41         if (n <= 0)
42         {
43             printf("0\n");
44             continue;
45         }
46         for (__int64 i = 1; i <= n; ++ i)
47         {
48             __int64 temp = gcd(i, n);
49             sum += my_pow(3, temp);
50         }
51         if (n & 1)
52             sum += n * my_pow(3, (n + 1) >> 1);
53         else
54         {
55             sum += (n >> 1) * my_pow(3, (n + 2) >> 1);
56             sum += (n >> 1) * my_pow(3, n >> 1);
57         }
58         printf("%I64d\n", sum / 2 / n);
59     }
60     return 0;
61 }

猜你喜欢

转载自www.cnblogs.com/GetcharZp/p/9557245.html
今日推荐