Problem Description
蜘蛛牌是windows xp操作系统自带的一款纸牌游戏,游戏规则是这样的:只能将牌拖到比她大一的牌上面(A最小,K最大),如果拖动的牌上有按顺序排好的牌时,那么这些牌也 跟着一起移动,游戏的目的是将所有的牌按同一花色从小到大排好,为了简单起见,我们的游戏只有同一花色的10张牌,从A到10,且随机的在一行上展开,编 号从1到10,把第i号上的牌移到第j号牌上,移动距离为abs(i-j),现在你要做的是求出完成游戏的最小移动距离。
 

Input
第一个输入数据是T,表示数据的组数。
每组数据有一行,10个输入数据,数据的范围是[1,10],分别表示A到10,我们保证每组数据都是合法的。
 

Output
对应每组数据输出最小移动距离。
 

Sample Input
1
1 2 3 4 5 6 7 8 9 10
 

Sample Output
9

思路:dfs,搜一遍剪枝即可!

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <cmath>
 5 using namespace std;
 6 
 7 const int n=10;
 8 int a[12],front[12],back[12],ans,b[3],c[12],v;
 9 bool f[12];
10 
11 void close()
12 {
13// fclose(stdin);
14 //fclose(stdout);
15 }
16 
17 void dfs(int cnt)
18 {
19 if (v>ans) return;
20 //printf("v:%d cnt:%d\n",v,cnt);
21 if (cnt==10)
22 {
23     if (v<ans)
24     {
25     ans=v;
26 //    return;
27     }
28     return;
29 }
30   for (int i=1;i<n;i++)
31   {
32       if (not f[i])
33       {
34           for (int j=i+1;j<=n;j++)
35           {
36               if (not f[j])
37               {
38                  f[i]=true;
39                   v+=(int)abs((double)a[i]-(double)a[j]);
40                   dfs(cnt+1);
41                   v-=(int)abs((double)a[i]-(double)a[j]);
42                   break;
43               }
44           }
45           f[i]=false;
46       }
47     }
48 }
49 
50 void init()
51 {
52 //freopen("spider.in","r",stdin);
53 //freopen("spider.out","w",stdout);
54 int t;
55 scanf("%d",&t);
56    while (t--)
57    {
58         int yy;
59         ans=0x3f3f3f;
60         for (int i=1;i<=n;i++)
61         {
62         //    yy=i;
63             scanf("%d",&yy);
64             a[yy]=i;
65         }
66         memset(f,false,sizeof(f));
67         v=0;
68         dfs(1);
69 printf("%d\n",ans);
70     }
71 }
72 
73 int main ()
74 {
75 init();
76 close();
77 return 0;
78 }

 

posted on 2012-12-28 17:56  cssystem  阅读(232)  评论(0编辑  收藏  举报