USACO Section3.2 msquare

Problem Summary

Given the initial and target configurations of the magic board, and three basic transformations, compute a minimal sequence of basic transformations.

Solution

There are at most 8!=40320 configurations, so it is acceptable to use BFS.
To avoid excessive memory usage, I use Cantor expansion to get hash value of configurations.

Assume C=(c[1],c[2],…,c[n-1],c[n]) is a configuration of integers 1,2,..n , then the hash value of C is:
f(C) = a[1](n-1)!+a[2](n-2)!+…+a[i](n-i)!+…+a[n-1]1!+a[n]*0!
(0<=a[i]<=n-i, 1<=i<=n)

a[i]: the number of the numbers that is smaller than c[i] in c[i+1],c[i+2],..,c[n]

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include <iostream>
#include <fstream>
#include <cstring>
#include <algorithm>
using namespace std;
struct Square
{
int config[8];
} target;
Square init = { .config = {1,2,3,4,5,6,7,8} };
struct Node
{
Square sq;
int steps,last;
char opr;
};
int head,tail;
Node qu[40330];
bool vis[41000];
const int tr[][8]={
{7,6,5,4,3,2,1,0},
{3,0,1,2,5,6,7,4},
{0,6,1,3,4,2,5,7}
};
const int factorial[]={1,1,2,6,24,120,720,5040};
void transform(int mode,const Square &st,Square &res)
{
for(int i=0;i<8;i++)
res.config[i]=st.config[tr[mode][i]];
}
int cantor(Square *a)
{
int res=0,t;
for(int i=0;i<7;i++)
{
t=0;
for(int j=i+1;j<8;j++)
if(a->config[j]>a->config[i])
t++;
res+=t*factorial[7-i];
}
return res;
}
int main()
{
fstream fin("msquare.in",ios::in);
fstream fout("msquare.out",ios::out);
for(int i=0;i<8;i++) fin>>target.config[i];
int tar_cantor=cantor(&target);
if(cantor(&init)==tar_cantor)
{
fout<<0<<endl<<endl;
fin.close();
fout.close();
return 0;
}
head=0; tail=1;
qu[0].sq=init;
qu[0].steps=0;
qu[0].last=0;
vis[cantor(&init)]=true;
int idx=0;
Node cur;
Square tmp;
bool flag=false;
while(head<tail)
{
cur=qu[head];
head++;
for(int i=0;i<3;i++)
{
transform(i,cur.sq,tmp);
int j=cantor(&tmp);
if(vis[j]) continue;
vis[j]=true;
qu[tail].sq=tmp;
qu[tail].steps=cur.steps+1;
qu[tail].last=head-1;
qu[tail].opr='A'+i;
tail++;
if(j==tar_cantor)
{
idx=tail-1;
flag=true;
break;
}
}
if(flag) break;
}
fout<<qu[idx].steps<<endl;
int count=0,i=0;
char ans[200];
while(idx>0)
{
ans[i]=qu[idx].opr;
idx=qu[idx].last;
i++;
}
i--;
count=0;
while(i>=0)
{
fout<<ans[i];
i--;
count++;
if(count%60==0)
{
count=0;
fout<<endl;
}
}
if(count) fout<<endl;
fin.close();
fout.close();
return 0;
}