light oj 1005 - Rooks (组合数学)

来源:互联网 发布:软件开发模型演进 编辑:程序博客网 时间:2024/05/18 20:32
      1005 - Rooks
 PDF (English)StatisticsForum
Time Limit: 1 second(s)Memory Limit: 32 MB

A rook is a piece used in the game of chess which is playedon a board of square grids. A rook can only move vertically or horizontallyfrom its current position and two rooks attack each other if one is on the pathof the other. In the following figure, the dark squares represent the reachablelocations for rook R1 from its current position. The figurealso shows that the rookR1 andR2 are inattacking positions whereR1 andR3 arenot. R2 and R3 are also in non-attackingpositions.

Now, given two numbers n and k, your job is todetermine the number of ways one can putk rooks on ann x nchessboard so that no two of them are in attacking positions.

Input

Input starts with an integer T (≤ 350),denoting the number of test cases.

Each case contains two integers n (1 ≤ n ≤30) and k (0 ≤ k ≤ n2).

Output

For each case, print the case number and total number ofways one can put the given number of rooks on a chessboard of the given size sothat no two of them are in attacking positions. You may safely assume that thisnumber will be less than1017.

Sample Input

Output for Sample Input

8

1 1

2 1

3 1

4 1

4 2

4 3

4 4

4 5

Case 1: 1

Case 2: 4

Case 3: 9

Case 4: 16

Case 5: 72

Case 6: 96

Case 7: 24

Case 8: 0



在n*n的棋盘里放车,车相同,求方法数,,,
这题已经推导出是组合数了,,我是一个一个考虑放第一个有几种情况,第二个有几种情况然后类推去重,,,,然而去重考虑情况太多,,,,
其实这题透过题目看本质,从全局考虑只要不在路径上就是 n行选k个组合,n列选k个排列,就能保证不在路径上,而且不用逐个考虑,,,思维的差距往往就是一步,,
从局部到全局的转变


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <climits>
using namespace std;
typedef long long LL;
LL A(int n,int m);
LL C(int n,int m);


int main()
{
    int t, ncase=1;
    scanf("%d", &t);
    while(t--)
    {
        int n, m;
        scanf("%d %d", &n, &m);
        if(m>n)
        {
            printf("Case %d: 0\n",ncase++);
            continue;
        }
        LL ans=A(n,m)*C(n,m);
        printf("Case %d: %lld\n",ncase++,ans);
    }
    return 0;
}


LL A(int n,int m)
{
    LL ans=1;
    for(int i=n-m+1;i<=n;i++)
    {
        ans*=i;
    }
    return ans;
}


LL C(int n,int m)
{
    LL ans=1;
    for(int i=1;i<=m;i++)
    {
        ans=ans*(n-i+1)/i;
    }
    return ans;
}

 

0 0
原创粉丝点击