【poj2741】 Colored Cubes

http://poj.org/problem?id=2741 (题目链接)

题意

  给出n个骰子,每一面都有一种颜色,问最少更改多少个面的颜色可以使所有骰子通过旋转后完全相同。

solution

  迷之dfs。

  设6个面的编号为1~6,从中选一个作为顶面,再选一个作为正面,那么其它面都可以确定(因为有对面的面也确定了),因此每个骰子有6*4=24种姿态,每种姿态对应一个全排列P,P[i]表示i所在的位置。所以我们手打这24种排列。 

  接下来看看如何暴力。我们考虑先枚举每个立方体的姿态(第一个作为“参考系”,不用枚举),然后对于6个面分别选一个出现次数最多的颜色作为“标准”,和它不同的颜色一律重新上色。那么姿态的组合一共有24³(注意第一个立方体不用枚举),算上常数,应该可以过。 

  再有就是读入的时候,将字符串全部转换成数字,方便操作。

代码

// poj2741
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<string>
#include<vector>
#define LL long long
#define inf 2147483640
#define Pi 3.1415926535898
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;

vector<string> names;
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},
};//24种姿态

int n,ans,dice[4][6],r[6],color[4][6];

int ID(char* name) {
    string s(name);
    int n=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];
    int tot=0;
    for (int j=0;j<6;j++) {
        int cnt[24];
        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;//第d个立方体的姿态
            dfs(d+1);
        }
}
int main() {
    while (scanf("%d",&n)!=EOF && 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);//记录第i个立方体第j个面上的颜色
            }
        ans=n*6;//赋初值为最大
        r[0]=0;
        dfs(1);
        printf("%d
",ans);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/MashiroSky/p/5916174.html