1027 打印沙漏 (20 分)
本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印
*****
***
*
***
*****
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。
输入格式:
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。
输出格式:
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。
输入样例:
19 *
输出样例:
2
#include<iostream>
#include<bits/stdc++.h>
#include<algorithm>
#include<string>
#include<stack>
using namespace std;
int main(){
int N,row=0;
char c;
cin>>N>>c;
for(int i=0;i<N;i++){
if((2*i*(i+2)+1)>N){
row=i-1;
break;
}
}
for(int i=row;i>=1;i--){
for(int k=row-i;k>=1;k--) cout<<" ";
for(int j=i*2+1;j>=1;j--) cout<<c;
cout<<endl;
}
for (int i=0;i<row;i++) cout<<" ";
cout <<c<<endl;
for(int i=1;i<=row;i++){
for (int k=row-i;k>=1;k--) cout<<" ";
for (int j=i*2+1;j>=1;j--) cout<<c;
cout<<endl;
}
cout<<(N-(2*row*(row+2)+1));
}
#include<iostream>
#include<bits/stdc++.h>
#include<algorithm>
#include<string>
#include<stack>
using namespace std;
//2*row+1 2*row-1 ... ... 3 1 (1) 3 ... ... 2*row-1 2*row+1 -1 Sn=n(a1+an)/2
//(row+1)*(1+2*row+1)/2 * 2 -1=2*(row+1)^2 -1<=n 2*(row+1)^2<=n+1;
void q_di(int *p_row,int *p_yushu,int n){
*p_row=1;
while((*p_row+1)*(*p_row+1)*2<=(n+1)){
++*p_row;
}
--*p_row;
*p_yushu=(n+1)-(*p_row+1)*(*p_row+1)*2;
}//求行数和剩余个数
void shuchu(int geshu,char c){
while(geshu-->0){
putchar(c);
}
}
void hua_shalou(int konggeshu,int fuhaoshu,char c){
//空格数,符号数,字符
shuchu(konggeshu,' ');//空格数一开始是0个
shuchu(fuhaoshu,c); //符号数 row*2+1 刚开始 2 * 2 +1 =5
putchar('\n');
if(fuhaoshu==1){
return ;
}
if(fuhaoshu>1){
hua_shalou(konggeshu+1,fuhaoshu-2,c);//执行第二次时 空格数=1,符号数-2
shuchu(konggeshu,' '); //
shuchu(fuhaoshu,c); //2*2+1-2=3
putchar('\n');
}
}
int main(){
int n;
char c;
cin>>n>>c;
int row,yushu;
q_di(&row,&yushu,n);
hua_shalou(0,row*2+1,c);//一开始0个空格
printf("%d\n",yushu);
}
还没有评论,来说两句吧...