Queue

来源:互联网 发布:快反部队知乎 编辑:程序博客网 时间:2024/06/13 16:55
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
1026576
1

一开始用dfs所以愉快的超时了,后来看到网上有人提供思路用dp,将每次队列i人看作是从i-1人的状态变化过来。不妨认为加入的是最矮的,可以插在末尾或者队首或者队伍中间,所以得到状态转移方程f[i][j][k]=f[i-1][j][k-1]+f[i-1][j-1][k]+(i-2)*f[i-1][j][k],i代表当前队伍总人数,j代表从头向后看的人数,k代表从后向前看的人数。
#include<iostream>#include<string.h>using namespace std;int n,p,q;long long f[15][15][15];void prepare(){    int i,j,k;    memset(f,0,sizeof(f));    f[1][1][1]=1;    for(i=2;i<=13;i++)        for(j=1;j<=i;j++)            for(k=1;k<=i;k++)                f[i][j][k]=f[i-1][j][k-1]+f[i-1][j-1][k]+(i-2)*f[i-1][j][k];}int main(){    int T;    cin>>T;    prepare();    while(T--)    {        cin>>n>>p>>q;        cout<<f[n][p][q]<<endl;    }    return 0;}





0 0
原创粉丝点击