題目鏈接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1259
——————————————————————————————————
題目描述:
給立方體着色,如果兩個立方體經過各種旋轉後,能夠各個對應面的顏色完全相同,則這兩個立方體就是相同的。(鏡面對稱是不行的,即只交換相對面的顏色)
現在給n個立方體(n小於4),並且把立方體各個面的顏色告訴你,問最少更改幾個面的顏色可以讓這n個立方體相同。
——————————————————————————————————
題目思路:
這題真坑死我了,我努力地想了半天有什麼精妙的解法,甚至拿出了奧數知識。。結果發現,n很小,可以直接暴力出來。。
暴力的方法有很多種,一種是把立方體的各種存在形式枚舉(即旋轉24次,6個面*4 = 24次),一種是暴力改顏色。
顯然第二種是不好想的。所以用了第一種方法,並且先把立方體各種所能存在的狀態枚舉在最前面,大大降低了思考的難度。
——————————————————————————————————
題目細節:
1、事先枚舉好狀態,可以大大降低了思考的難度和出錯的概率。
2、看到題,如果一下找不到思路,可以試下暴力這條路,當然前提是分析好數據規模。
——————————————————————————————————
題目代碼:
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
#define min(a,b) ((a)>(b)? (b):(a))
#define max(a,b) ((a)>(b)? (a):(b))
struct hash
{
char s[30];
int flag;
}hash[30];
int cube[5][7],now[5][7];
int n = 0;
int sta[24][6] = {{0,1,2,3,4,5},{0,2,4,1,3,5},{0,4,3,2,1,5},{0,3,1,4,2,5},
{1,0,3,2,5,4},{1,3,5,0,2,4},{1,5,2,3,0,4},{1,2,0,5,3,4},
{2,1,5,0,4,3},{2,5,4,1,0,3},{2,4,0,5,1,3},{2,0,1,4,5,3},
{3,1,0,5,4,2},{3,0,4,1,5,2},{3,4,5,0,1,2},{3,5,1,4,0,2},
{4,0,2,3,5,1},{4,2,5,0,3,1},{4,5,3,2,0,1},{4,3,0,5,2,1},
{5,1,3,2,4,0},{5,3,4,1,2,0},{5,4,2,3,1,0},{5,2,1,4,3,0}};
int ans = 0;
int hashfun(char *s)
{
int h = 0;
int len = 0;
int i = 0;
len = strlen(s);
for(i = 0;i<len;i++)
h += s[i];
h = h%25;
while(1)
{
if(!hash[h].flag)
{
hash[h].flag = 1;
strcpy(hash[h].s,s);
return h;
}
else if(strcmp(hash[h].s,s) != 0)
h++;
else return h;
}
}
void solve(int cur)
{
int i = 0,j = 0;
if(cur == n)
{
int dif = 0;
int a[5],p = 0,q = 0,at[5];
for(i = 1;i<=6;i++)
now[n][i] = cube[n][i];
for(i = 1;i<=6;i++)
{
p = 0;
q = 0;
for(j = 0;j<5;j++)
at[j] = 0;
for(j = 1;j<=n;j++)
{
for(q = 0;q<p;q++)
if(now[j][i] == a[q])
{
at[q]++;
continue;
}
a[p] = now[j][i];
at[p++]++;
}
q = 0;
for(j = 0;j<p;j++)
q = max(q,at[j]);
dif += n-q;
}
ans = min(dif,ans);
return;
}
for(i = 0;i<24;i++)
{
for (j = 1;j <7;j++)
{
now[cur][j] = cube[cur][sta[i][j-1]+1];
}
solve(cur + 1);
}
}
int main()
{
int t = 0,i = 0,j = 0;
char s[30];
while((scanf("%d",&n),n))
{
for(i = 0;i<30;i++)
hash[i].flag = 0;
for(i = 1;i<=n;i++)
{
for(j = 1;j<=6;j++)
{
scanf("%s",s);
cube[i][j] = hashfun(s);
}
}
ans = 24;
solve(1);
printf("%d\n",ans);
}
return 0;
}