标签:
Inspired by a "Little Bishops" problem, Petya now wants to solve problem for rooks.
A rook is a piece used in the game of chess which is played on a board of square grids. A rook can only move horizontally and vertically from its current position and two rooks attack each other if one is on the path of the other.
Given two numbers n and k, your job is to determine the number of ways one can put k rooks on an n × n chessboard so that no two of them are in attacking positions.
受到“Little BIshops”问题的启发,Petya现在想要解决关于车的问题。
车是方形网格棋盘上的一枚棋子。它只能横向或者纵向移动,如果有别的车在它的路线上,那么它们可以相互攻击。
给定两个数字n和k,你的任务是求在n × n的棋盘上放置k个车,使得他们不相互攻击的方案数。
The input file contains two integers n (1 ≤ n ≤ 10) and k (0 ≤ k ≤ n^2).
输入包含两个整数n (1 <= n <= 10)和k (0 <= k <= n^2)。
Print a line containing the total number of ways one can put the given number of rooks on a chessboard of the given size so that no two of them are in attacking positions.
输出一行,包含在给定大小的棋盘上放置给定数量的车,使得它们不相互攻击的方案数。
4 4
24
首先,车只会横向或者纵向攻击,那么我们只要保证这k个车每个都独占一行一列,那么它们的相对位置一共有k!种情况。
下面考虑棋盘大小,如果n < k,那么不能满足k个车不能每个都独占一行一列。由于我们只需要放置k行k列,那么一共有C(n, k) * C(n , k)种情况。
那么答案为:C(n, k) * C(n, k) * k!,化简得:n! * n! / (k! * (n - k)! * (n - k)!),考虑到可能会溢出,我们改变一下运算顺序。
即:ans = n! / (k! * (n - k)!) * n! / (n - k)!。
对于阶乘的计算,可以直接打表,最大只需要10!。
#include <iostream> #include <algorithm> using namespace std; const int MAX = 16; unsigned long long f[MAX]; int main() { f[0] = 1; for(int i = 1; i < MAX; i++) { f[i] = f[i - 1] * i; } int N, K; while(cin >> N >> K) { if(K > N) { cout << 0 << endl; } else { cout << f[N] / f[K] / f[N - K] * f[N] / f[N - K] << endl; } } return 0; }
一开始还以为类似八皇后,准备写Check函数,后来发现只是简单的排列组合而已。
标签:
原文地址:http://www.cnblogs.com/Ivy-End/p/4320272.html