Algorithm


problem Link : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1069 

There is a queue with N people. Every person has a different heigth. We can see P people, when we are looking from the beginning, and R people, when we are looking from the end. Its because they are having different height and they are covering each other. How many different permutations of our queue has such a interesting feature? Input The input consists of T test cases. The number of them (1 ≤ T ≤ 10000) is given on the first line of the input file. Each test case begins with a line containing a single integer number N that indicates the number of people in a queue (1 ≤ N ≤ 13). Then follows line containing two integers. The first integer corresponds to the number of people, that we can see looking from the beginning. The second integer corresponds to the number of people, that we can see looking from the end. Output For every test case your program has to determine one integer. Print how many permutations of N people we can see exactly P people from the beginning, and R people, when we are looking from the end.

Sample Input 3 10 4 4 11 3 1 3 1 2

Sample Output 90720 10265

Code Examples

#1 Code Example with C Programming

Code - C Programming

 #include <bits/stdc++.h>
using namespace std;

int main()
{
    // use 20 because test queries contains > 13
    long long dp[20][20][20];
    memset(dp,0,sizeof(dp));
    dp[1][1][1] = 1; // dp[N][P][R]
    // assume we are choosing the spot of the shortest person
    // he has to be in the next front, next back, or any middle spot
    for(int N=2;N < 14;N++)
    for(int P=1;P < =N;P++)
    for(int R=1;R < =N;R++){
        // choose any spot not at either end, there are N-2 positions
        long long middle = dp[N-1][P][R]*(N-2);
        // either end
        long long front = dp[N-1][P-1][R];
        long long back = dp[N-1][P][R-1];
        dp[N][P][R] = middle+front+back;
    }
    int t,n,p,r;
    cin >> t;
    while(t--){
        cin >> n >> p >> r;
        printf("%lld\n", dp[n][p][r]);
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
3
10 4 4
11 3 1
3 1 2

Output

x
+
cmd
90720
1026576
1
Advertisements

Demonstration


UVA Online Judge solution - 10128 - Queue - UVA Online Judge solution in C,C++,Java

Previous
UVA Online Judge solution - 10125 - Sumsets - UVA Online Judge solution in C,C++,Java
Next
UVA Online Judge solution - 10130 - SuperSale - UVA Online Judge solution in C,C++,Java