题目链接: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; }