题解:UVA13214 The Robot's Grid

· · 题解

这是一道可癌的数学题。

前置知识

思路

直接暴击会超时,考虑使用数学知识,我们发现它到达终点需要水平移动 c - 1 次,竖直移动 r - 1 次,一共需要移动 c + r - 2 次,那么我们可以考虑使用组合数解决问题,我们需要预处理组合数,众所周知 C[i][j] = C[i - 1][j - 1] + C[i - 1][j],特判 i = 0j = 0 的情况,每次查询只需要输出 C[c + r - 2][c - 1] 即可,时间复杂度 O(q)

Code

#include<bits/stdc++.h>
#define int long long
using namespace std;
int Q,n,m,C[51][51];
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    for(int i = 0;i <= 50;i ++){
        C[i][0] = 1;
        for(int j = 1;j <= i;j ++){
            C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
        }
    }
    cin >> Q;
    while(Q --){
        cin >> n >> m;
        cout << C[n + m - 2][n - 1] << '\n';
    }
    return 0;
}