一个正方体只要确认上顶面和前面的两个面就能被确定下来,那么上顶面有六种情况,在上顶面被确认的前提下,前面有四种情况,所以一个正方体通过旋转一共有24中姿态,只要把这可能的26种姿态的排列,打印出来,然后在主函数里枚举匹配即可。
下面是枚举可行排列的代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int Left[6]={4,0,2,3,5,1};
int Up[6]={2,1,5,0,4,3};
void rotate(int *T,int *p)
{
int q[6];
memcpy(q,p,sizeof(int)*6);
for(int i=0;i<6;i++) p[i]=T[q[i]];
}
void enumerate_permutations()
{
int p[6];
int p0[6]={0,1,2,3,4,5};
for(int i=0;i<6;i++){
memcpy(p,p0,sizeof(int)*6);
if(i==0) {rotate(Up,p);}
if(i==1) {rotate(Left,p);rotate(Up,p);}
if(i==3) {rotate(Up,p);rotate(Up,p);}
if(i==4) {rotate(Left,p);rotate(Left,p);rotate(Left,p);rotate(Up,p);}
if(i==5) {rotate(Left,p);rotate(Left,p);rotate(Up,p);}
for(int j=0;j<4;j++){
printf("{%d,%d,%d,%d,%d,%d},",p[0],p[1],p[2],p[3],p[4],p[5]);
rotate(Left,p);
}
}
printf("\n");
}
int main()
{
enumerate_permutations();
return 0;
}
下面是最后程序的代码:
//
// main.cpp
// Richard
//
// Created by 邵金杰 on 16/9/28.
// Copyright © 2016年 邵金杰. All rights reserved.
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
int dice24[24][6]={
{2,1,5,0,4,3},{2,0,1,4,5,3},{2,4,0,5,1,3},{2,5,4,1,0,3},{4,2,5,0,3,1},{5,2,1,4,3,0},
{1,2,0,5,3,4},{0,2,4,1,3,5},{0,1,2,3,4,5},{4,0,2,3,5,1},{5,4,2,3,1,0},{1,5,2,3,0,4},
{5,1,3,2,4,0},{1,0,3,2,5,4},{0,4,3,2,1,5},{4,5,3,2,0,1},{1,3,5,0,2,4},{0,3,1,4,2,5},
{4,3,0,5,2,1},{5,3,4,1,2,0},{3,4,5,0,1,2},{3,5,1,4,0,2},{3,1,0,5,4,2},{3,0,4,1,5,2}
};
const int maxn=4;
int n,ans;
int color[maxn][6],dice[maxn][6];
int r[maxn];
vector<string> names;
int ID(const char *name)
{
string s(name);
int n=(int)names.size();
for(int i=0;i<n;i++)
if(names[i]==s) return i;
names.push_back(s);
return n;
}
void check()
{
for(int i=0;i<n;i++)
for(int j=0;j<6;j++)
color[i][dice24[r[i]][j]]=dice[i][j];//dice24[r[i]][j]代表经过第r[i]种变化之后,j位置的颜色转到的新位置
int tot=0;
for(int j=0;j<6;j++){
int cnt[maxn*6];
memset(cnt,0,sizeof(cnt));
int maxface=0;
for(int i=0;i<n;i++)
maxface=max(maxface,++cnt[color[i][j]]);
tot+=n-maxface;
}
ans=min(ans,tot);
}
void dfs(int d)
{
if(d==n) check();
else for(int i=0;i<24;i++){
r[d]=i;
dfs(d+1);
}
}
int main()
{
while(scanf("%d",&n)==1&&n)
{
names.clear();
for(int i=0;i<n;i++)
for(int j=0;j<6;j++){
char name[30];
scanf("%s",name);
dice[i][j]=ID(name);
}
ans=n*6;
r[0]=0;
dfs(1);
printf("%d\n",ans);
}
return 0;
}