首頁  >  文章  >  後端開發  >  C程序:求解停靠站問題

C程序:求解停靠站問題

WBOY
WBOY轉載
2023-09-11 20:17:021025瀏覽

C程序:求解停靠站問題

問題陳述- 一個程序,用於查找火車在n 個車站中的r 個車站停靠的方式,以便沒有兩個停靠站是連續的。

問題解釋

該程式將計算火車停靠的方式數,即排列。在這裡,火車將從點X行駛到Y。在這些點之間,有n個網站。列車將在這n個車站中的r個車站停靠,條件是在r車站停靠時,列車不應在連續兩個車站停靠.

可以使用直接的npr 公式找到此排列。

讓我們舉幾個例子, p>

Input : n = 16 , r = 6
Output : 462

解釋 - 使用以下給出的排列公式找到火車可以在滿足條件的16 個站點中的6 個站點停靠的方式數:

npr 或p(n, r) = n! ∕ (n-r)!

演算法

Input  : total numbers of stations n and number of stations train can stop r.
Step 1 : For values of n and r calculate the value of p(n,r) = n! / (n-r)!
Step 2 : print the value of p(n,r) using std print method.

範例

現場示範

#
#include<stdio.h>
int main(){
   int n = 16, s = 6;
   printf("Total number of stations = %d</p><p>Number of stopping station = %d</p><p>", s, n);
   int p = s;
   int num = 1, dem = 1;
   while (p!=1) {
      dem*=p;
      p--;
   }
   int t = n-s+1;
   while (t!=(n-2*s+1)) {
      num *= t;
      t--;
   }
   if ((n-s+1) >= s)
      printf("Possible ways = %d", num / dem);
   else
      printf("no possible ways");
}

輸出

Total number of stations = 16
Number of stopping station = 6
Possible ways = 462

以上是C程序:求解停靠站問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除