一、问题描述
二、问题分析
第一个想法依然是对所有元素进行遍历,如C/C++代码,然后确实还有可以改进的空间,在计算一次循环序列的过程中,很容易发现,在这个循环节中间的所有元素都满足要求,那么我们就可以讲这些元素存储下来,无需对其再次求循环序列,如Python代码。但是在实现过程中,我选择使用了列表进行存储,导致搜索和计算中的复杂度大大变高,使得计算时间变得相当长,但是整体思想和代码没有问题,感兴趣的话可以对Python版本的代码进行进一步的优化。
三、代码实现
1.C/C++实现
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cctype>
using namespace std;
// 根据当前序列生成下一个序列
void get_next(int* cur, int size=6)
{
int next[6], index = 0;
memset(next, 0, sizeof(next));
for (int i = cur[0]; i < size; i++)
next[index++] = cur[i];
for (int i = 0; i < cur[0]; i++)
next[index++] = 7 - cur[i]; // 翻转对应相加为7
for (int i = 0; i < size; i++)
cur[i] = next[i];
}
int get_int(int* arr, int len)
{
int tmp = 0;
for (int i = 0; i < len; i++)
{
tmp *= 10;
tmp += arr[i];
}
return tmp;
}
int main()
{
int count = 0;
int cur[6];
int loop[6];
for (loop[0] = 0; loop[0] < 6; loop[0]++)
for (loop[1] = 0; loop[1] < 6; loop[1]++)
for (loop[2] = 0; loop[2] < 6; loop[2]++)
for (loop[3] = 0; loop[3] < 6; loop[3]++)
for (loop[4] = 0; loop[4] < 6; loop[4]++)
for (loop[5] = 0; loop[5] < 6; loop[5]++)
{
for (int i = 0; i < 6; i++)
cur[i] = loop[i] + 1;
vector<int> list;
auto iter = list.end();
// 尝试生成循环并存储
while (iter == list.end())
{
list.push_back(get_int(cur, 6));
get_next(cur, 6);
iter = find(list.begin(), list.end(), get_int(cur, 6));
}
// 找到循环圈,但不包含初始元素
if (iter != list.begin())
count++;
}
cout << count << endl;
return 0;
}
2.Python实现
# coding = utf-8
# 生成所有的初始可能
def generator():
tmp = [1] * 6
while True:
yield tmp[:]
if sum(tmp) == 6 * 6:
return
tmp[-1] += 1
for i in range(5, -1, -1):
if tmp[i] >= 7:
tmp[i] -= 6
tmp[i - 1] += 1
# 生成下一个序列
def get_next(cur):
next_list = cur[cur[0]:]
for i in range(cur[0]):
next_list.append(7 - cur[i])
return next_list
def get_count():
ok_list = []
count = 0
for item in generator():
if item in ok_list:
continue
tmp_list = [item[:]]
while True:
item = get_next(item)
if item in tmp_list:
break
tmp_list.append(item[:])
if item != tmp_list[0]:
count += 1
k = 0
for i in range(len(tmp_list)):
if tmp_list[i] == item:
k = i
break
ok_list.extend(tmp_list[k:])
return count
if __name__ == '__main__':
print(get_count())
pass