There are n intermediate train stations between point X and point Y. Calculate the number of different ways in which a train can be arranged to stop at s stations so that no two stations are adjacent to each other. Therefore, in this article, we will explain various possible ways to find out the number of stops. Looking at this problem, we can see that we need to find combinations that allow the train to stop at s stations.
Let us give an example: there are eight intermediate stations and we need to find a way to stop the train at three intermediate stations.
n = 8, s = 3
We also have (n - s) stations, that is, five stations where the train cannot stop,
We have five stations A, B , C, D, E, the train cannot stop. Now we have six points to arrange the three stops so that no two stops are consecutive. Therefore, the number of ways is -
6<sub>c<sub>3</sub></sub>= [fact(6) - fact(3)] / fact(3) = 6 * 5 * 4 / 3 * 2 * 1 = 20
There are 20 ways to schedule three stops from point X and point Y. So here is the Chinese translation of Example -
Input : n = 15 s = 4 Output : 495 Input : n = 8 s = 3 Output : 20
#include<bits/stdc++.h> using namespace std; int main(){ int n = 8, s = 3; int flag1 = 1, flag2 = 1, temp = s, ans; // selecting 's' positions out of 'n-s+1' int x = n - s + 1; while (x != (n - 2 * s + 1)) { flag1 = flag1 * x; x--; } while (temp != 1) { flag2 = flag2 * temp; temp--; } ans = flag1 / flag2; if ((n - s + 1) >= s) cout << "Number of ways : " << ans; else cout << "not possible to find"; return 0; }
Number of ways : 20
To understand this C code, we can break the solution into several steps.
Take the number of stations in number n and the stop station in s as input.
Initialize the flag1 and flag 2 variables with 1 and store the value of s in the temp variable.
Calculate flag1, which is the numerator [fact(n) -fact(r)].
Calculate flag2, which is the denominator [fact(r)]
Print the result.
In this article we solved the problem of finding the number of ways a train can stop at an intermediate station such that there are no two stations is continuous. We also learned a C program to solve this problem and a complete method to solve this problem. We can write the same program in other languages, such as C, java, python and other languages.
The above is the detailed content of Using C++ programming, find the number of stops. For more information, please follow other related articles on the PHP Chinese website!