Java程序解决车站数量问题
在 A 和 B 两地之间有 12 个中间站。求一列火车在其中 4 个中间站停靠的方式有多少,使得没有两个停靠站是连续的?
例子 -
Input : n = 12, s = 4
Output : 126
Input : n = 16, s = 5
Output : 792
// Java code to calculate number
// of ways of selecting 'p' non
// consecutive stations out of
// 'n' stations
import java.io.*;
import java.util.*;
class GFG {
public static int stopping_station(int p, int n)
{
int num = 1, dem = 1, s = p;
// selecting 's' positions out of 'n-s+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)
System.out.print(num / dem);
else
// if conditions does not satisfy of combinatorics
System.out.print("not possible");
return 0;
}
public static void main(String[] args)
{
// n is total number of stations
// s is no. of stopping stations
int n, s;
// arguments of function are
// number of stopping station
// and total number of stations
stopping_station(4, 12);
}
}
// ""This code is contributed by Mohit Gupta_OMG ""
输出:
126
更多详情请参考完整文章停站数问题!