USACO 4.4 Shuttle Puzzle(dfs)
比较有意思的一个题,虽然不知道为什么这么做。。。看样例就可以发现一般是w_ _b wb_ _bw只能这样4种操作。。。没想到就这样过了。。注意了一下20个换行,2Y。。。我开始还在想bfs还想过,直接构造,构造不出来。。。
1 /* 2 ID:cuizhe 3 LANG: C++ 4 TASK: shuttle 5 */ 6 #include <iostream> 7 #include <cstdio> 8 #include <map> 9 #include <algorithm> 10 #include <cstring> 11 #include <string> 12 using namespace std; 13 map<string,int> mp; 14 char str[32]; 15 int que[100001]; 16 int a[100001]; 17 int ans = 10000000; 18 int n; 19 int judge() 20 { 21 int i; 22 for(i = 0; i < n; i ++) 23 if(str[i] != '2') 24 break; 25 if(i == n&&str[n] == ' ') 26 return 1; 27 else 28 return 0; 29 } 30 void dfs(int x,int step) 31 { 32 int i; 33 if(ans <= step) return; 34 if(judge()) 35 { 36 if(step-1 < ans) 37 { 38 ans = step-1; 39 for(i = 1;i <= ans;i ++) 40 a[i] = que[i]; 41 } 42 return ; 43 } 44 if(x-1 >= 0&&x-2 >= 0&&str[x-1] == '2'&&str[x-2] == '1') 45 { 46 que[step] = x-2; 47 str[x-2] = ' '; 48 str[x] = '1'; 49 dfs(x-2,step+1); 50 str[x-2] = '1'; 51 str[x] = ' '; 52 } 53 if(x-1 >= 0&&str[x-1] == '1') 54 { 55 que[step] = x-1; 56 str[x] = '1'; 57 str[x-1] = ' '; 58 dfs(x-1,step+1); 59 str[x] = ' '; 60 str[x-1] = '1'; 61 } 62 if(x+1 <= 2*n&&x+2 <= 2*n&&str[x+1] == '1'&&str[x+2] == '2') 63 { 64 que[step] = x+2; 65 str[x+2] = ' '; 66 str[x] = '2'; 67 dfs(x+2,step+1); 68 str[x+2] = '2'; 69 str[x] = ' '; 70 } 71 if(x+1 <= 2*n&&str[x+1] == '2') 72 { 73 que[step] = x+1; 74 str[x] = '2'; 75 str[x+1] = ' '; 76 dfs(x+1,step+1); 77 str[x] = ' '; 78 str[x+1] = '2'; 79 } 80 return ; 81 } 82 int main() 83 { 84 int i; 85 freopen("shuttle.in","r",stdin); 86 freopen("shuttle.out","w",stdout); 87 scanf("%d",&n); 88 for(i = 0; i < n; i ++) 89 { 90 str[i] = '1'; 91 str[n+i+1] = '2'; 92 } 93 str[n] = ' '; 94 dfs(n,1); 95 for(i = 1;i <= ans;i ++) 96 { 97 if(i%20 == 0||i == ans) 98 printf("%d\n",a[i]+1); 99 else 100 printf("%d ",a[i]+1); 101 } 102 return 0; 103 }