给定整数N ,其中4≤N≤100 。垂直有N行,水平有N行。因此,有N 2个交叉点。任务是找到将4个项目放置在这N 2个位置中的方法,以使每一行和每一列最多包含一个项目。
例子:
Input: N = 4
Output: 24
Input: N = 5
Output: 600
方法:从n中选择4条水平线的方式为n C 4 。在这些行的第一行中有n种方法可以放置项目。给定第一个项目的位置,有n-1种方法可以将项目放置在这些行的第二行上,因为已经采用了一条垂直线。给定第一个和第二个项目的位置,有n-2种方法可以将项目放置在第三行上, n-3的方法也可以相同。在选定的4条水平路径上放置项目的方式总数为n *(n-1)*(n-2)*(n-3) 。因此,结果为n C 4 * n *(n – 1)*(n – 2)*(n – 3) 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the number of ways
// to place 4 items in n^2 positions
long long NumberofWays(int n)
{
long long x = (1LL * (n) * (n - 1) * (n - 2) * (n - 3))
/ (4 * 3 * 2 * 1);
long long y = (1LL * (n) * (n - 1) * (n - 2) * (n - 3));
return (1LL * x * y);
}
// Driver code
int main()
{
int n = 4;
cout << NumberofWays(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the number of ways
// to place 4 items in n^2 positions
static long NumberofWays(int n)
{
long x = (1l * (n) * (n - 1) * (n - 2) * (n - 3))
/ (4 * 3 * 2 * 1);
long y = (1l * (n) * (n - 1) * (n - 2) * (n - 3));
return (1l * x * y);
}
// Driver code
public static void main(String args[])
{
int n = 4;
System.out.println( NumberofWays(n));
}
}
// This code is contributed by Arnab Kundu
Python3
# python implementation of the approach
# Function to return the number of ways
# to place 4 items in n^2 positions
def NumbersofWays(n):
x = (n * (n - 1) * (n - 2) * (n - 3)) // (4 * 3 * 2 * 1)
y = n * (n - 1) * (n - 2) * (n - 3)
return x * y
# Driver code
n = 4
print(NumbersofWays(n))
# This code is contributed by Shrikant13
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the number of ways
// to place 4 items in n^2 positions
public static long NumberofWays(int n)
{
long x = (1l * (n) * (n - 1) * (n - 2) *
(n - 3)) / (4 * 3 * 2 * 1);
long y = (1l * (n) * (n - 1) * (n - 2) *
(n - 3));
return (1l * x * y);
}
// Driver code
public static void Main(string[] args)
{
int n = 4;
Console.WriteLine(NumberofWays(n));
}
}
// This code is contributed by Shrikant13
PHP
输出:
24