USACO 3.2 Magic Squares
空间问题比较头疼,需要康拓展开时间换空间。
TASK: msquare
LANG: C++
Compiling...
Compile: OK
Executing...
Test 1: TEST OK [0.000 secs, 3280 KB]
Test 2: TEST OK [0.000 secs, 3280 KB]
Test 3: TEST OK [0.000 secs, 3280 KB]
Test 4: TEST OK [0.000 secs, 3280 KB]
Test 5: TEST OK [0.000 secs, 3280 KB]
Test 6: TEST OK [0.027 secs, 3280 KB]
Test 7: TEST OK [0.027 secs, 3280 KB]
Test 8: TEST OK [0.027 secs, 3280 KB]
All tests OK.
1 /*
2 PROG: msquare
3 ID: jiafeim1
4 LANG: C++
5 */
6
7 #include <iostream>
8 #include <fstream>
9
10 using namespace std;
11
12 #include <queue>
13 bool haveDo[50000] = {false};
14
15 std::queue<unsigned int> work;
16
17 unsigned int solve[1000];
18 unsigned int pre[50000];
19 int solve_count = 0;
20 int fact[10]={1,1,2,6,24,120,720,5040,40320};
21 unsigned int cantor(unsigned long in)
22 {
23 int i,temp,k,j;
24 unsigned int toReturn=0;
25 bool haveDo[8]={false};
26 for (i=8;i>=2;i--)
27 {
28 k=in>> 3*(i-1);
29 in-=k<<3*(i-1);
30 haveDo[k]=true;
31 temp=k;
32 for (j=0;j<=k-1;j++)
33 if (haveDo[j])
34 temp--;
35 toReturn+=fact[i-1]*temp;
36 }
37 return toReturn;
38 }
39 int main()
40 {
41 ifstream fin("msquare.in");
42 ofstream fout("msquare.out");
43
44 unsigned int temp;
45 unsigned int target = 0;
46 unsigned int base = 343980;
47 for (int i = 8 * 8 * 8 * 8 * 8 * 8 * 8; i >= 8*8*8*8; i /= 8)
48 {
49 fin >> temp;
50 target += i * (temp - 1);
51 }
52 for (int i = 1; i <= 8*8*8; i *= 8)
53 {
54 fin >> temp;
55 target += i * (temp - 1);
56 }
57 work.push(base);
58
59 while (!work.empty())
60 {
61 unsigned int cur = work.front();
62
63 if (cur == target)
64 {
65 break;
66 }
67
68 unsigned int toGo,t1,t2,t3,t4,whe;
69 work.pop();
70
71 toGo = ((cur & 16773120) >> 12) + ((cur & 4095) << 12);
72 whe = cantor(toGo);
73 if (!haveDo[whe])
74 {
75 haveDo[whe] = true;
76 pre[whe] = cur;
77 work.push(toGo);
78 }
79
80 toGo = ((cur & 16748536) >> 3) + ((cur & 28679) << 9);
81 whe = cantor(toGo);
82 if (!haveDo[whe])
83 {
84 haveDo[whe] = true;
85 pre[whe] = cur;
86 work.push(toGo);
87 }
88
89 t1 = (cur&1835008)>>3;
90 t2 = (cur&229376) >>12;
91 t3 = (cur&448) << 12;
92 t4 = (cur&56)<<3;
93 toGo = (cur&14712327)+t1+t2+t3+t4;
94 whe = cantor(toGo);
95 if (!haveDo[whe])
96 {
97 haveDo[whe] = true;
98 pre[whe] = cur;
99 work.push(toGo);
100 }
101 }
102 unsigned int now = target;
103
104 while(now != base)
105 {
106 solve[solve_count++] = now;
107 now = pre[cantor(now)];
108 }
109 int line_count =0;
110 fout<<solve_count<<endl;
111 for(int i = solve_count-1;i>=0;--i,base=solve[i+1])
112 {
113 now = solve[i];
114 if(line_count>=60) fout<<endl;
115 if((base&56)==(now&229376)>>12)
116 {
117 fout<<'A';
118 continue;
119 }
120 if((base&56)==(now&7)<<3)
121 {
122 fout<<'B';
123 continue;
124 }
125 if((base&56)==(now&448)>>3)
126 {
127 fout<<'C';
128 continue;
129 }
130
131 }
132 if(solve_count%60 != 0 || solve_count == 0) fout<<endl;
133 fin.close();
134 fout.close();
135
136 return 0;
137 }