USACO Section 4.4 Shuttle Puzzle - Hash都不用的DFS水题..
2012-01-23 12:53
411 查看
龙年第一题~~~这题开始以为搜索会超时~~要用构造才行~~我这找了好久规律~~也没找出构造的方法~~~就写搜索了...
搜索的时候要注意方法和顺序...显然的是W只能往右移..B只能往左移~~否则不可能得到最小步数的解~~然后也能想到的其实只要每次都保证了W右移,B左移~~最小总步数一开始就是确定的...而如果在移的时候先尝试WB_ -> _BW...再尝试W_ -> _W 再尝试_B -> B_ 再尝试 _WB -> BW_ 这个顺序来找结果..那么最后得到的一定也是字典序最小的..这样来写..Hash是不需要的..因为不可能出现重复的情况...所以若DFS找到了第一组解~~就可以退出DFS了..这就是答案~~我这样子来搜结果...最大的输入数据20都能秒出~~~
Program:
/* ID: zzyzzy12 LANG: C++ TASK: shuttle */ #include<iostream> #include<istream> #include<stdio.h> #include<string.h> #include<math.h> #include<stack> #include<map> #include<algorithm> #include<queue> #define oo 2000000005 #define ll long long #define pi (atan(2)+atan(0.5))*2 using namespace std; int n,way[100005],num; string str,s; bool DFS(int p) { way[++num]=p; if (s==str) return true; if (p!=2 && s[p-1]=='B' && s[p-2]=='W') { s[p]='W'; s[p-2]=' '; if (DFS(p-2)) return true; s[p]=' '; s[p-2]='W'; } if (p!=1 && s[p-1]=='W') { s[p]='W'; s[p-1]=' '; if (DFS(p-1)) return true; s[p]=' '; s[p-1]='W'; } if (p!=n*2+1 && s[p+1]=='B') { s[p]='B'; s[p+1]=' '; if (DFS(p+1)) return true; s[p]=' '; s[p+1]='B'; } if (p!=n*2 && s[p+1]=='W' && s[p+2]=='B') { s[p]='B'; s[p+2]=' '; if (DFS(p+2)) return true; s[p]=' '; s[p+2]='B'; } num--; return false; } int main() { freopen("shuttle.in","r",stdin); freopen("shuttle.out","w",stdout); scanf("%d",&n); s=" "; int i; str=" "; for (i=1;i<=n;i++) { s+='W'; str+='B'; } s+=' '; str+=' '; for (i=1;i<=n;i++) { s+='B'; str+='W'; } num=-1; DFS(n+1); printf("%d",way[1]); for (i=2;i<=num;i++) { if (i%20==1) printf("\n%d",way[i]); else printf(" %d",way[i]); } printf("\n"); return 0; }
相关文章推荐
- 【COGS & USACO Training】710. 命名那个数字(hash+水题+dfs)
- USACO 4.4 Shuttle Puzzle(dfs)
- USACO-Section 4.4 Shuttle Puzzle (BFS)
- usaco 4.4 Shuttle Puzzle(字符hash+搜索)
- USACO section 2.4 Overfencing(dfs+bfs)
- USACO-Section 2.1 Hamming Codes (DFS)
- USACO-Section 2.1 The Castle(DFS)
- USACO Section 4.1 Cryptcowgraphy - BT的DFS剪枝..
- USACO-Section 4.2 The Perfect Stall (二分图最大匹配[匈牙利算法[DFS]||网络流[Ford-Fulkerson]])
- USACO Section 5.2 Wisconsin Squares - 按要求DFS就行了..
- USACO section 2.3 Controlling Companies(dfs)
- USACO section 3.3 Riding the Fences(欧拉通路的遍历,dfs)
- POJ1164 + USACO Section 2.1 The Castle - 简单的DFS...
- USACO 4.4 shuttle puzzle
- USACO Section 1.4 - Mother's Milk(DFS + 记忆化)
- USACO section 2.3 Controlling Companies(dfs)
- USACO section 3.3 Riding the Fences(欧拉通路的遍历,dfs)
- USACO section 1.5 Checker Challenge(dfs深搜)
- USACO(含training section)水题合集[5/未完待续]
- USACO section 1.5 Checker Challenge(dfs深搜)