USACO4.4 Shuttle Puzzle【bfs+优化】
直接上$bfs$,每一个状态记录下当前字符串的样子,空格的位置,和走到这个状态的答案。
用空格的位置转移,只有$50pts$
考虑到题目一个性质:$W$只往右走,$B$只往左走,就可以过了。
1 #include<cstdio> 2 #include<algorithm> 3 #include<vector> 4 #include<cstring> 5 #include<queue> 6 #include<map> 7 #include<iostream> 8 using namespace std; 9 #define ll long long 10 #define INF 0x3f3f3f3f 11 struct node{ 12 int pos; 13 string s,ans; 14 }; 15 int n; 16 queue<node>Q; 17 map<string,bool>vis; 18 string aim; 19 string bfs() 20 { 21 node st;string aim=""; 22 st.s=""; 23 for(int i=1;i<=n;i++) 24 st.s+='W',aim+='B'; 25 st.s+='@',aim+='@'; 26 for(int i=1;i<=n;i++) 27 st.s+='B',aim+='W'; 28 st.pos=n; 29 Q.push(st); 30 vis[st.s]=1; 31 while(!Q.empty()) 32 { 33 node now=Q.front();Q.pop(); 34 if(now.s==aim) 35 return now.ans; 36 //cout<<now.s<<endl; 37 int idx=now.pos,len=now.s.size(); 38 node nxt=now; 39 if(idx-2>=0&&nxt.s[idx-2]!=nxt.s[idx-1]&&nxt.s[idx-2]=='W') 40 { 41 nxt.s[idx]=nxt.s[idx-2]; 42 nxt.s[idx-2]='@'; 43 //cout<<nxt.s<<endl;// 44 char ch='0'+idx-2; 45 nxt.ans=now.ans+ch; 46 nxt.pos=idx-2; 47 if(!vis[nxt.s]) 48 Q.push(nxt); 49 vis[nxt.s]=1; 50 } 51 nxt=now; 52 if(idx-1>=0&&nxt.s[idx-1]=='W') 53 { 54 nxt.s[idx]=nxt.s[idx-1]; 55 nxt.s[idx-1]='@'; 56 //cout<<nxt.s<<endl;// 57 char ch='0'+idx-1; 58 nxt.ans=now.ans+ch; 59 nxt.pos=idx-1; 60 if(!vis[nxt.s]) 61 Q.push(nxt); 62 vis[nxt.s]=1; 63 } 64 nxt=now; 65 if(idx+1<len&&nxt.s[idx+1]=='B') 66 { 67 nxt.s[idx]=nxt.s[idx+1]; 68 nxt.s[idx+1]='@'; 69 char ch='0'+idx+1; 70 nxt.ans=now.ans+ch; 71 nxt.pos=idx+1; 72 if(!vis[nxt.s]) 73 Q.push(nxt); 74 vis[nxt.s]=1; 75 } 76 nxt=now; 77 if(idx+2<len&&nxt.s[idx+2]!=nxt.s[idx+1]&&nxt.s[idx+2]=='B') 78 { 79 nxt.s[idx]=nxt.s[idx+2]; 80 nxt.s[idx+2]='@'; 81 char ch='0'+idx+2; 82 nxt.ans=now.ans+ch; 83 nxt.pos=idx+2; 84 if(!vis[nxt.s]) 85 Q.push(nxt); 86 vis[nxt.s]=1; 87 } 88 } 89 return ""; 90 } 91 int main() 92 { 93 //freopen("shuttle.in","r",stdin); 94 //freopen("shuttle.out","w",stdout); 95 scanf("%d",&n); 96 string c=bfs(); 97 //cout<<c<<endl; 98 int tot=0; 99 for(int i=0;i<c.size();i++) 100 { 101 tot++; 102 printf("%d",c[i]-'0'+1); 103 if(tot==20||i==c.size()-1) 104 { 105 puts(""); 106 tot=0; 107 } 108 else printf(" "); 109 } 110 return 0; 111 }
转载请注明出处,有疑问欢迎探讨
博主邮箱 2775182058@qq.com