蓝桥杯 算法训练 未名湖边的烦恼 (递推,递归)

来源:互联网 发布:索尼z5 xz对知乎 编辑:程序博客网 时间:2024/05/29 05:02

算法训练 未名湖边的烦恼  
时间限制:1.0s   内存限制:256.0MB
    
问题描述
  每年冬天,北大未名湖上都是滑冰的好地方。北大体育组准备了许多冰鞋,可是人太多了,每天下午收工后,常常一双冰鞋都不剩。
  每天早上,租鞋窗口都会排起长龙,假设有还鞋的m个,有需要租鞋的n个。现在的问题是,这些人有多少种排法,可以避免出现体育组没有冰鞋可租的尴尬场面。(两个同样需求的人(比如都是租鞋或都是还鞋)交换位置是同一种排法)
输入格式
  两个整数,表示m和n
输出格式
  一个整数,表示队伍的排法的方案数。
样例输入
3 2
样例输出
5
数据规模和约定
  m,n∈[0,18]
  问题分析

参考博客:http://www.cnblogs.com/zhaopAC/p/5088856.html

递归:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int m, n;int f(int x, int y) {if(m - x == 0 || n - y == 0) {return 1;}else if(x == y) {return f(x + 1, y);}else if(x > y) {return f(x + 1, y) + f(x, y + 1);}}int main() {//freopen("input.txt", "r", stdin);scanf("%d %d", &m, &n);if(m < n) printf("0\n");else printf("%d\n", f(0, 0));return 0;}

递推:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int main () {int m, n;scanf("%d %d", &m, &n);int f[20][20];int i, j;memset(f, 0, sizeof(f));for(i = 1; i <= m; i++) {f[i][0] = 1;}for(i = 1; i <= m; i++) {for(j = 1; j <= n; j++) {if(i == j) f[i][j] = f[i][j - 1];else if(i > j) f[i][j] = f[i - 1][j] + f[i][j - 1];}}printf("%d\n", f[m][n]);return 0;}


0 0
原创粉丝点击