递归和简单dfs 近期题目整理2.0( 二 )


3. - 4117
题目描述:
将正整数n 表示成一系列正整数之和,n=n1+n2+…+nk, 其中n1>=n2>=…>=nk>=1,k>=1。
正整数n 的这种表示称为正整数n 的划分 。正整数n 的不同的划分个数称为正整数n 的划分数 。
AC代码:
#includeusing namespace std;int dfs(int a,int b){if(a == 0) return 1;if(b == 0) return 0;if(a >= b) return dfs(a - b,b) + dfs(a,b - 1); //分为使用b减和不使用b减两种情况if(a < b) return dfs(a,b - 1);}int main(){int n;while(cin >> n){int ans = dfs(n,n);cout << ans << endl;}return 0;}
这个题也是一个DFS的题目,构造一个DFS(N,N),前一个N是指的被减数,后面的N是指的减数,所以DFS回溯的临界就是被减数减为0,此时返回1,如果减数为0,则返回0.
4.Paths on a Grid
题目描述:
you areyour mathat . Once again, you are boredyourtellsthat youyears ago So youto waste your time withart .
you have a piece ofpaper and youaof size n*m on the paper. Let’s call thiswith the lines ita grid.at the lower leftof the grid, you move yourto the upper right ,care that it stays on the lines and moves only to the right or up. Theis shown on the left:
a , isn’t it?theone more time, youwith theshown on the right. Now you : how manyworks of art can you ?
Input:
The input. Each isby two32-bitn and m,the size of the . As you can , theof lines of thegrid is one more in each . Input isby n=m=0.
:
For each test caseon a line theofart works that can beusing theabove. That is, how many paths are there on a grid where each step of the pathofone unit to the right or one unit up? You maythat thisfits into a 32-bit.
AC代码:
#include#include#include#includeusing namespace std;long long n,m,ans,x;long long getc(long long a,long long b){long long s = 1;for(long long i = 1;i <= b;i++){s = s*(a - b + i)/i; }return s;}int main(){while(~scanf("%lld %lld",&n, &m)&&(n != 0||m != 0)){ans = 0;x = n;if(m < n) x = m;printf("%lld\n",getc(m + n,x));}return 0;}
我们这样想,既然只能走上方向或者右方向,也就是说走的总数是不变的m+n,为了省时间我们可以选择m,n中最小的那一个赋值给x,然后C(m+n,x)就可以了 。(我做的时候给T了10次TAT,所以一定要注意选择求C(m+n,x)的方法 。
5.51Nod - 1073 约瑟夫环
题目描述:
N个人坐成一个圆环(编号为1 - N),从第1个人开始报数,数到K的人出列,后面的人重新从1开始报数 。问最后剩下的人的编号 。
例如:N = 3,K = 2 。2号先出列,然后是1号,最后剩下的是3号 。
(自杀游戏)
AC代码:
#includeint f(int n, int m){if(n==1)return 0;else return (f(n-1,m)+m)%n;} int main(){int m, n;scanf("%d %d",&n,&m);printf("%d\n", f(n,m)+1);return 0;}
直白说,这个约瑟夫环套的公式QAQ…