算法课后作业第二题

来源:互联网 发布:菜鸟裹裹抢单软件 编辑:程序博客网 时间:2024/06/05 19:10
/***********************************************************求倒入p杯酒,第m层的第n个杯子的酒量    copyright qinxiankang@gmail.com                             2013301500100 计科三班 秦贤康                2015.10.24               ***********************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>//#define DEBUG 1/*** @desc:求倒入p杯酒,第m层的第n个杯子里有多少酒* @author: 秦贤康* @param: int m 层数* @param: int n 杯子编号* @param: int p 导入的酒量(杯)* @return:int 酒量* @date: 2015-10-24*/int wine(int m, int n, int p);/*** @desc:求编号为n的杯子所在行号* @author: 秦贤康* @param: int n 杯子编号* @return:int 行号* @date: 2015-10-24*/int floor(int n);/*** @desc:求第n层杯子数* @author: 秦贤康* @param: int n 层数* @return:int 杯子总数* @date: 2015-10-24*/int cup_num(int n);int main(void){unsigned long long int m,n,p;scanf("%d%d%d",&m,&n,&p);p = wine(m,n,p);printf("%d\n",p>750?750:p);return 0;}/*** @desc:求倒入p杯酒,第m层的第n个杯子里有多少酒* @author: 秦贤康* @param: int m 层数* @param: int n 杯子编号* @param: int p 导入的酒量(杯)* @return:int 酒量* @date: 2015-10-24*/int wine(int m, int n, int p){if(m*(m+1)/2<n || n==0)return 0;/* 如果第m层没有n杯酒 ,递归出口*/ if(m==1)return p*750;/* 第一层没有下层,递归出口 */ int total=0, cup[3]={0,0,0},j=1;cup[0]=n;for(int i=1;i<=cup_num(n-1);i++)/* 遍历上一层的所有杯子 */{int fi = floor(i);/* fi:当前第1个杯子所在行数 */if( fi+i == n || fi+i+1 == n){/* 查找上一层的杯子 */cup[j]= i;j++;}}#ifdef DEBUGint g=5-m;while(g--)printf("    ");printf("%d-%d=:%d %d %d\n",m,n,cup[0],cup[1],cup[2]);#endifint a,b,c;a = wine(m-1, cup[0], p);b = wine(m-1, cup[1], p);c = wine(m-1, cup[2], p);a = a>750?a-750:0;/* 酒不足750不会溢出 */b = b>750?b-750:0;c = c>750?c-750:0;total = a/3+b/3+c/3;/* 这层酒来自上层的3杯酒 */ #ifdef DEBUGg=5-m;while(g--)printf("    ");printf("<=%d-%d=%d\n",m,n,total);#endif//if(total >750)return 750;/*如果溢出,则只有一杯酒容量 */ return total;} /*** @desc:求编号为n的杯子所在行号* @author: 秦贤康* @param: int n 杯子编号* @return:int 行号* @date: 2015-10-24*/int floor(int n){int i=1;while(n>=1){if(i*(i+1) / 2 >=n)return i;i++;}return 0;}/*** @desc:求第n层杯子数* @author: 秦贤康* @param: int n 层数* @return:int 杯子总数* @date: 2015-10-24*/int cup_num(int n){return floor(n)*( floor(n)+1 )/2;}

0 0
原创粉丝点击