USACO 1.4.2 The Clocks

深搜4^9次就可以了,不用剪枝就可以过,主要还是要模拟钟表的顺时针变化,代码上注释比较清楚。。所以就不多说了。

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 //x数组用于记录九种方法,初始化
 5 int x[11][5]={{0,0,0,0,0},{1,2,4,5,0},{1,2,3,0,0},{2,3,5,6,0},{1,4,7,0,0},{2,4,5,6,8},{3,6,9,0,0},{4,5,7,8,0},{7,8,9,0,0},{5,6,8,9,0}};
 6 int p[11],q[11],first; //p数组用于看改变后的钟表位置,q用于记录初始值
 7 int f[11];  //f记录0,1,2,3的排列,最多每种方法用3次
 8 void cals(int f[])
 9 {
10     int i,j,k,t,ok=0;
11     for(i=1;i<=9;i++)
12     {
13         for(j=0;f[i]&&(j<5)&&(x[i][j]>0);j++)
14         {
15             p[x[i][j]]=(p[x[i][j]]+f[i])%4;  //核心步骤,按要求模拟变换,把3,6,9,12换为1,2,3,0
16         }
17     }
18     for(i=1;i<=9;i++)
19         if(p[i]!=0) {ok=1;break;}  //如果全是12点了,标记已经找到
20     if(!ok)
21     {
22         first=0;
23         for(i=1;i<=9;i++)
24         {
25             if(f[i]!=0)   //按f[i]个数输出i
26             {
27                 for(k=1;k<=f[i];k++)
28                     if(!first)
29                         {first=1;printf("%d",i);}
30                     else printf(" %d",i);
31             }
32         }
33         printf("\n");
34     }
35     else
36     {
37         for(i=1;i<=9;i++)
38             p[i]=q[i]; //q初始化为原来值
39     }
40 }
41 void dfs(int cur)  //4^9次深搜
42 {
43     int i;
44    if(cur>9)
45    {
46        cals(f);
47    }
48    else
49    {
50        for(i=0;i<=3;i++)
51        {
52             f[cur]=i;
53             dfs(cur+1);
54        }
55    }
56 }
57 int main()
58 {
59     freopen("clocks.in","r",stdin);
60     freopen("clocks.out","w",stdout);
61     int i,j,c;
62     for(i=1;i<=9;i++)
63     {
64         scanf("%d",&c);
65         p[i]=(c/3)%4;  //数据简单处理
66         q[i]=p[i];
67     }
68     dfs(1);
69     return 0;
70 }

Executing...

   Test 1: TEST OK [0.054 secs, 2052 KB]

   Test 2: TEST OK [0.054 secs, 2052 KB]

   Test 3: TEST OK [0.054 secs, 2052 KB]

   Test 4: TEST OK [0.032 secs, 2052 KB]

   Test 5: TEST OK [0.054 secs, 2052 KB]

   Test 6: TEST OK [0.054 secs, 2052 KB]

   Test 7: TEST OK [0.065 secs, 2052 KB]

   Test 8: TEST OK [0.043 secs, 2052 KB]

   Test 9: TEST OK [0.054 secs, 2052 KB]

 

All tests OK.

posted @ 2013-10-14 17:35  hjf007  阅读(260)  评论(0编辑  收藏  举报