您的位置:首页 > 其它

poj 1166 The Clocks (暴力|| dfs)

2016-09-20 13:38 302 查看
The Clocks

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 16196 Accepted: 6627
Description

|-------|    |-------|    |-------|

|       |    |       |    |   |   |

|---O   |    |---O   |    |   O   |

|       |    |       |    |       |

|-------|    |-------|    |-------|

A            B            C

|-------|    |-------|    |-------|

|       |    |       |    |       |

|   O   |    |   O   |    |   O   |

|   |   |    |   |   |    |   |   |

|-------|    |-------|    |-------|

D            E            F

|-------|    |-------|    |-------|

|       |    |       |    |       |

|   O   |    |   O---|    |   O   |

|   |   |    |       |    |   |   |

|-------|    |-------|    |-------|

G            H            I

(Figure 1)


There are nine clocks in a 3*3 array (figure 1). The goal is to return all the dials to 12 o'clock with as few moves as possible. There are nine different allowed ways to turn the dials on the clocks. Each such way is called a move. Select for each move a number
1 to 9. That number will turn the dials 90' (degrees) clockwise on those clocks which are affected according to figure 2 below. 
Move   Affected clocks

1         ABDE

2         ABC

3         BCEF

4         ADG

5         BDEFH

6         CFI

7         DEGH

8         GHI

9         EFHI

(Figure 2)


Input

Your program is to read from standard input. Nine numbers give the start positions of the dials. 0=12 o'clock, 1=3 o'clock, 2=6 o'clock, 3=9 o'clock.
Output

Your program is to write to standard output. Output a shortest sorted sequence of moves (numbers), which returns all the dials to 12 o'clock. You are convinced that the answer is unique.
Sample Input
3 3 0
2 2 2
2 1 2

Sample Output
4 5 8 9


分析:每一个时钟最多转3次,所以,枚举一下,4^9次方,用dfs,最后判断是否符合即可,把数量最少的存一下。网上还有优化的算法4^4
代码如下:

#include <stdio.h>
int a[10];
int b[10];
int fin[1005];
int min = 1000;
int add[9][9] = {
//A,B,C,D,E,F,G,H,I
{1,1,0,1,1,0,0,0,0},
{1,1,1,0,0,0,0,0,0},
{0,1,1,0,1,1,0,0,0},
{1,0,0,1,0,0,1,0,0},
{0,1,0,1,1,1,0,1,0},
{0,0,1,0,0,1,0,0,1},
{0,0,0,1,1,0,1,1,0},
{0,0,0,0,0,0,1,1,1},
{0,0,0,0,1,1,0,1,1}
};

void dfs(int t)
{
int i, j, k;
if (t == 9)
{
int temp[10], count=0;
for (i = 0; i < 9; i++)
temp[i] = a[i];
for (i = 0; i < 9; i++)
for (k = 0; k < b[i]; k++)
for (j = 0; j < 9; j++)
{
temp[j] = (temp[j] + add[i][j]) % 4;
count++;
}
int sum = 0;
for (i = 0; i < 9; i++)
sum += temp[i];
if (sum == 0 && count/9 < min)
{
min = 0;
for (i = 0; i < 9; i++)
{
for (j = 0; j < b[i]; j++)
{
fin[min++] = i+1;
}
}
}
return ;
}
for (i = 0; i < 4; i++)
{
b[t] = i;
dfs(t + 1);
}

}

int main()
{
int i,j;
//freopen("input.txt","r",stdin);
for (i = 0; i < 9; i++)
scanf("%d",a+i);
dfs(0);
for (i = 0; i < min; i++)
printf("%d ", fin[i]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: