生活随笔
收集整理的這篇文章主要介紹了
洛谷P2730 [IOI]魔板 Magic Squares
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目背景
在成功地發明了魔方之后,魯比克先生發明了它的二維版本,稱作魔板。這是一張有8個大小相同的格子的魔板:
1 2 3 4
8 7 6 5
題目描述
我們知道魔板的每一個方格都有一種顏色。這8種顏色用前8個正整數來表示??梢杂妙伾男蛄衼肀硎疽环N魔板狀態,規定從魔板的左上角開始,沿順時針方向依次取出整數,構成一個顏色序列。對于上圖的魔板狀態,我們用序列(1,2,3,4,5,6,7,8)來表示。這是基本狀態。
這里提供三種基本操作,分別用大寫字母“A”,“B”,“C”來表示(可以通過這些操作改變魔板的狀態):
“A”:交換上下兩行;
“B”:將最右邊的一列插入最左邊;
“C”:魔板中央四格作順時針旋轉。
下面是對基本狀態進行操作的示范:
A: 8 7 6 5
1 2 3 4
B: 4 1 2 3
5 8 7 6
C: 1 7 2 4
8 6 3 5
對于每種可能的狀態,這三種基本操作都可以使用。
你要編程計算用最少的基本操作完成基本狀態到目標狀態的轉換,輸出基本操作序列。
輸入格式
只有一行,包括8個整數,用空格分開(這些整數在范圍 1——8 之間)不換行,表示目標狀態。
輸出格式
Line 1: 包括一個整數,表示最短操作序列的長度。
Line 2: 在字典序中最早出現的操作序列,用字符串表示,除最后一行外,每行輸出60個字符。
輸入輸出樣例
輸入 #1復制 2 6 8 4 5 7 3 1 輸出 #1復制 7
BCABCCB
說明/提示
題目翻譯來自NOCOW。
USACO Training Section 3.2
?
解析:-----BFS寬搜-----
對于狀態采用了字符串的存儲是采用了將八個數字壓成一個字符串的方式
例如初始狀態為"12345678",而字符串存儲為"12348765"?。
然后根據三個變換規則ABC進行變換
直到變成了目標狀態
注意目標狀態也要第二部分翻轉
例如"26845731",存儲為"26841375"。
1 #include<iostream>
2 #include<cstdio>
3 #include<cmath>
4 #include<cstring>
5 #include<
string>
6 #include<algorithm>
7 #include<iomanip>
8 #include<cstdlib>
9 #include<queue>
10 #include<
set>
11 #include<map>
12 #include<stack>
13 #include<vector>
14 #define LL long long
15 #define re register
16 #define Max 100001
17 struct MoBan {
18 std::
string p;
19 std::
string str;
20 int step;
21 };
22 std::queue<MoBan>
q;
23 std::
string D;
24 int ans;
25 std::map<std::
string,
int>
m;
26 std::
string BFS()
27 {
28 MoBan now,net;
29 while(!
q.empty()) {
30 now=
q.front();q.pop();
31 std::
string str=
now.str;
32 int t=
now.step;
33 std::
string p=
now.p;
34 if(str==
D) {
35 ans=
t;
36 return p;
37 break;
38 }
39 ++
t;
40 //A
41 std::
string d=
"";
42 for(re
int i =
4 ; i <=
7 ; ++ i) d+=
str[i];
43 for(re
int i =
0 ; i <=
3 ; ++ i) d+=
str[i];
44 net.str=d;net.p=p+
"A";
45 net.step=
t;
46 if(m[d]!=
1) q.push(net),m[d]=
1;
47 //B
48 std::
string a=
"";
49 a+=str[
3];
50 for(re
int i =
0 ; i <
3 ; ++ i) a+=
str[i];
51 a+=str[
7];
52 for(re
int i =
4 ; i <
7 ; ++ i) a+=
str[i];
53 net.str=a;net.p=p+
"B";
54 if(m[a]!=
1) q.push(net),m[a]=
1;
55 //C
56 std::
string c=
"";
57 c+=str[
0],c+=str[
5],c+=str[
1],c+=str[
3],c+=str[
4],c+=str[
6],c+=str[
2],c+=str[
7];
58 net.str=c;net.p=p+
"C";
59 if(m[c]!=
1) q.push(net),m[c]=
1;
60 }
61 }
62 int main()
63 {
64 char ch[
9];std::
string str=
"12348765";
65 for(re
int i =
1 ; i <=
8 ; ++ i) std::cin >>
ch[i];
66 for(re
int i =
1 ; i <=
4 ; ++ i) D+=
ch[i];
67 for(re
int i =
8 ; i >=
5 ; -- i) D+=
ch[i];
68 MoBan now;m[str]=
1;
69 now.p=
"";now.step=
0;now.str=str;q.push(now);std::
string p=
BFS();
70 printf(
"%d\n",ans);
71 int len=p.length();std::cout << p[
0];
72 for(re
int i =
1 ; i < len ; ++
i) {
73 std::cout <<
p[i];
74 if(i%
60==
0) std::cout <<
'\n';
75 }
76 return 0;
77 }
AC代碼
轉載于:https://www.cnblogs.com/handsomegodzilla/p/11287637.html
總結
以上是生活随笔為你收集整理的洛谷P2730 [IOI]魔板 Magic Squares的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。