1027 打印沙漏 (20 分)

╰半橙微兮° 2023-10-01 19:22 73阅读 0赞

本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印

  1. *****
  2. ***
  3. *
  4. ***
  5. *****

所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。

给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。

输入格式:
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。

输出格式:
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。

输入样例:
19 *
输出样例:





2

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. #include<algorithm>
  4. #include<string>
  5. #include<stack>
  6. using namespace std;
  7. int main(){
  8. int N,row=0;
  9. char c;
  10. cin>>N>>c;
  11. for(int i=0;i<N;i++){
  12. if((2*i*(i+2)+1)>N){
  13. row=i-1;
  14. break;
  15. }
  16. }
  17. for(int i=row;i>=1;i--){
  18. for(int k=row-i;k>=1;k--) cout<<" ";
  19. for(int j=i*2+1;j>=1;j--) cout<<c;
  20. cout<<endl;
  21. }
  22. for (int i=0;i<row;i++) cout<<" ";
  23. cout <<c<<endl;
  24. for(int i=1;i<=row;i++){
  25. for (int k=row-i;k>=1;k--) cout<<" ";
  26. for (int j=i*2+1;j>=1;j--) cout<<c;
  27. cout<<endl;
  28. }
  29. cout<<(N-(2*row*(row+2)+1));
  30. }

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. #include<algorithm>
  4. #include<string>
  5. #include<stack>
  6. using namespace std;
  7. //2*row+1 2*row-1 ... ... 3 1 (1) 3 ... ... 2*row-1 2*row+1 -1 Sn=n(a1+an)/2
  8. //(row+1)*(1+2*row+1)/2 * 2 -1=2*(row+1)^2 -1<=n 2*(row+1)^2<=n+1;
  9. void q_di(int *p_row,int *p_yushu,int n){
  10. *p_row=1;
  11. while((*p_row+1)*(*p_row+1)*2<=(n+1)){
  12. ++*p_row;
  13. }
  14. --*p_row;
  15. *p_yushu=(n+1)-(*p_row+1)*(*p_row+1)*2;
  16. }//求行数和剩余个数
  17. void shuchu(int geshu,char c){
  18. while(geshu-->0){
  19. putchar(c);
  20. }
  21. }
  22. void hua_shalou(int konggeshu,int fuhaoshu,char c){
  23. //空格数,符号数,字符
  24. shuchu(konggeshu,' ');//空格数一开始是0个
  25. shuchu(fuhaoshu,c); //符号数 row*2+1 刚开始 2 * 2 +1 =5
  26. putchar('\n');
  27. if(fuhaoshu==1){
  28. return ;
  29. }
  30. if(fuhaoshu>1){
  31. hua_shalou(konggeshu+1,fuhaoshu-2,c);//执行第二次时 空格数=1,符号数-2
  32. shuchu(konggeshu,' '); //
  33. shuchu(fuhaoshu,c); //2*2+1-2=3
  34. putchar('\n');
  35. }
  36. }
  37. int main(){
  38. int n;
  39. char c;
  40. cin>>n>>c;
  41. int row,yushu;
  42. q_di(&row,&yushu,n);
  43. hua_shalou(0,row*2+1,c);//一开始0个空格
  44. printf("%d\n",yushu);
  45. }

发表评论

表情:
评论列表 (有 0 条评论,73人围观)

还没有评论,来说两句吧...

相关阅读

    相关 1027.打印

    本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“\”,要求按下列格式打印 所谓“沙漏形状”,是指每