在 C++ 中,如何將專案放置在 n^2 個位置,使得每行每列最多隻有一個專案


在這個問題中,我們給定一個整數 n,表示垂直方向和水平方向各有 n 條線,這些線相交形成 n2 個交點。我們的任務是找到將 4 個專案放置在這些交點上的總方法數,

並且要求每行每列最多隻能放置一個專案。

讓我們舉個例子來理解這個問題,

輸入

n=4

輸出

24

解釋

為了解決這個問題,我們需要從 n 條水平線中選擇 4 條來放置專案,這可以透過 nC4 來計算。現在,每條水平線都有 n 條垂直線,因此在第一條選擇的水平線上放置專案有 n 種方法。然後,我們移動到下一條選擇的水平線,那裡將有 n-1 種可能的放置方式。以此類推,第三個可以在 n-2 種方式中放置,第四個可以在 n-3 種方式中放置。因此,總方法數將是 nC4*n*(n-1)*(n-2)*(n-3)

程式展示演算法的實現,

示例

 線上演示

#include <iostream>
using namespace std;
long long placeItems(int n) {
   return (1LL * (1LL *
   ((n) * (n - 1) * (n - 2) * (n - 3)) / (4 * 3 * 2 * 1)) *
   ((1LL * (n) * (n - 1) * (n - 2) * (n - 3))));
}
int main() {
   int n = 4;
   cout<<"The number of way is which 4 items can be placed in the intersection of "<<n;
   cout<<" lines vertically and horizotally are "<<placeItems(n);
   return 0;
}

輸出

The number of way is which 4 items can be placed in the intersection of 4 lines vertically and horizotally are 24

更新於: 2020-07-17

63 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.