PAT 1027 打印沙漏

这道题其实难度不算大,关键是有点坑。。。
下面讲讲我做此题的一些心得:
- 测试点2是白给,如果测试点2都过不了就完全是程序逻辑的问题。
- 测试点0和3 对应的是输出空格的问题,即当每行的字符输出完以后,无需再在其右侧输出空格。
- 测试点1 对应的是当所给数字恰好能构成一个沙漏时,也需输出0 (题目给的例子里是含糊的说明,所以这点有点迷。。。。)
解决完这三个问题,本题就迎刃而解啦!
下面附上代码:
#include <iostream>
#include<stdio.h>
using namespace std;
void output(int a,string b,int c) //c为总长度,a为每行的字符长度
{ for(int t=0;t<(c-a)/2;++t)
{
cout<<" ";
}
for(int j=(c-a)/2;j<(c-a)/2+a;++j)
{
cout<<b;
}
//for(int k=(c-a)/2+a;k<c;++k) ***右边空格无需打印**** 如果添加的话测试点0和3过不去
//{ // cout<<" "; //}
cout<<endl;
} //输入数字和字符即可输出
void output(int a ,string b) { for(int t=0;t<a;++t) { cout<<b; } }
void show(int a,string b)
{
int temp = 3;
if(a<7)
{
cout<<b;
//if(a-1 !=0) cout<<endl<<a-1; 即使正好可以组成一个沙漏,也要输出0,否则测试点1过不去
cout<<endl<<a-1;
}
else{
a = a-1;
while(a >= temp*2)
{
a = a-2*temp;
temp += 2;
}
temp = temp-2;
int flag = temp;
while(temp>0)
{
output(temp,b,flag);
temp = temp -2;
}
temp = 3;
while(temp<=flag)
{
if(temp==flag) output(temp,b);
else output(temp,b,flag);
temp =temp + 2;
}
//if(a!=0) cout<<endl<<a; 即使正好组成一个沙漏,也要输出0,否则测试点1过不去
cout<<endl<<a;
}
}
int main()
{
int input;
string x;
scanf("%d",&input);
cin>>x;
show(input,x);
return 0;
}

浙公网安备 33010602011771号