USACO 5.4 All Latin Squares(DFS)

打表水过。看的题解,置换的那个优化完全没有看懂。

 1 /*

 2 ID: cuizhe

 3 LANG: C++

 4 TASK: latin

 5 */

 6 #include <cstdio>

 7 #include <iostream>

 8 using namespace std;

 9 int r[11][11],c[11][11];

10 int ans,n;

11 void dfs(int x,int y)

12 {

13     int xx,yy,i;

14     if(x > n-1)

15     {

16         ans ++;

17         return ;

18     }

19     if(y+1 > n)

20     {

21         xx = x+1;

22         yy = 2;

23     }

24     else

25     {

26         xx = x;

27         yy = y+1;

28     }

29     for(i = 1;i <= n;i ++)

30     {

31         if(!r[x][i]&&!c[y][i])

32         {

33             r[x][i] = 1;

34             c[y][i] = 1;

35             dfs(xx,yy);

36             r[x][i] = 0;

37             c[y][i] = 0;

38         }

39     }

40 }

41 int main()

42 {

43     int cl[10],i;

44     freopen("latin.in","r",stdin);

45     freopen("latin.out","w",stdout);

46     cl[0] = 1;

47     for(i = 1;i <= 7;i ++)

48     cl[i] = i*cl[i-1];

49     scanf("%d",&n);

50     if(n == 7)

51     {

52         printf("12198297600\n");

53         return 0;

54     }

55     for(i = 1;i <= n;i ++)

56     {

57         r[i][i] = 1;

58         c[i][i] = 1;

59     }

60     dfs(2,2);

61     printf("%d\n",cl[n-1]*ans);

62     return 0;

63 }

 

你可能感兴趣的:(USACO)