usaco training 5.4.1 All Latin Squares 题解

来源:互联网 发布:蓝牙模块主动发送数据 编辑:程序博客网 时间:2024/06/10 03:53

【原题】

All Latin Squares

A square arrangement of numbers

1  2  3  4  52  1  4  5  33  4  5  1  24  5  2  3  15  3  1  2  4
is a 5 x 5 Latin Square because each whole number from 1 to 5 appears once and only once in each row and column.

Write a program that will compute the number of NxN Latin Squares whose first row is:

1 2 3 4 5.......N
Your program should work for any N from 2 to 7.

PROGRAM NAME: latin

INPUT FORMAT

One line containing the integer N.

SAMPLE INPUT (file latin.in)

5

OUTPUT FORMAT

A single integer telling the number of latin squares whose first row is 1 2 3 . . . N.

SAMPLE OUTPUT (file latin.out)

1344


【译题】

描述'

一种正方形的数字编排

1 2 3 4 52 1 4 5 33 4 5 1 24 5 2 3 15 3 1 2 4

是一个5×5的拉丁幻方,即每个1到5的整数在每行每列都出现且出现一次。 斜体文字 写个程序计算N×N的的拉丁幻方的总数且要求第一行是:

1 2 3 4 5.......N

2<=N<=7

[编辑]格式

PROGRAM NAME: latin

INPUT FORMAT

一行包含一个整数N

OUTPUT FORMAT

只有一行,表示拉丁正方形的个数,且拉丁正方形的第一行为 1 2 3 . . . N.

[编辑]SAMPLE INPUT (file latin.in)

5

[编辑]SAMPLE OUTPUT (file latin.out)

1344

【初步分析】明显就是搜索题。做过了那道The prime的题目,我对这种只要求横行和竖行不重复、且N<=7的题目非常的不屑。因为没有明显的搜索顺序,我直接按顺序搜索。

【小优化】当然,其实最后一行和最后一列都可以不搜。

【结果】前6个点秒过,第7个点即使开100s也过不去!只好厚着脸皮去网上看题解:其实答案的范围超过了int类型!这也太坑了吧!即使对于每一个解,使用O(1)的效率,也是A不过去的!匆匆看题解,有一个剪枝非常的快——我们强制把第一列搞成递增(1,2,3,。。n)最后再把解乘上(n-1)!

【后记】N<=7,明显是打表的节奏。加了优化后,我也要23s过,所以无奈只好打表了。

【代码】

/*PROG:latinID:juan1973LANG:C++*/#include<stdio.h>using namespace std;const int maxn=10;int a[maxn][maxn],n,i;long long ans;bool lie[maxn][maxn],hang[maxn][maxn];void count(int x,int y){  if (y>n)   {    x++;y=2;  }  int i;  if (x>=n)   {    int j,k;    for (i=2;i<=n;i++)    {      for (j=1;j<=n;j++)        if (!lie[i][j]) {k=j;break;}      if (hang[n][k]) return;hang[n][k]=true;    }    ans++;    for (i=1;i<=n;i++) hang[n][i]=false;    return;  }  for (i=1;i<=n;i++)    if (!lie[y][i]&&!hang[x][i])    {      a[x][y]=i;      lie[y][i]=true;hang[x][i]=true;      count(x,y+1);      lie[y][i]=false;hang[x][i]=false;    }}int main(){  freopen("latin.in","r",stdin);  freopen("latin.out","w",stdout);  scanf("%ld",&n);  if (n==7) {printf("12198297600\n");return 0;}  for (i=1;i<=n;i++)  {    a[1][i]=i;    lie[i][i]=true;    a[i][1]=i;    hang[i][i]=true;  }  count(2,2);  for (i=n-1;i>1;i--) ans*=(long long) (i);  printf("%lld\n",ans);  return 0;}

4 0