1027 打印沙漏(20 分)
本題要求你寫個程序把給定的符號打印成沙漏的形狀。例如給定17個“*”,要求按下列格式打印
*****
***
*
***
*****
所謂“沙漏形狀”,是指每行輸出奇數個符號;各行符號中心對齊;相鄰兩行符號數差2;符號數先從大到小順序遞減到1,再從小到大順序遞增;首尾符號數相等。
給定任意N個符號,不一定能正好組成一個沙漏。要求打印出的沙漏能用掉儘可能多的符號。
輸入格式:
輸入在一行給出1個正整數N(≤1000)和一個符號,中間以空格分隔。
輸出格式:
首先打印出由給定符號組成的最大的沙漏形狀,最後在一行中輸出剩下沒用掉的符號數。
輸入樣例:
19 *
輸出樣例:
*****
***
*
***
*****
2
#include<iostream>
using namespace std;
int main()
{
int n;
char c;
cin >> n >> c;
int remain = n - 1;
int temp = 0;
for (int i = 1; i < n; i++)
{
if (remain < temp)
break;
temp = (i * 2 + 1) * 2;// temp 爲3 7 9 乘2...
if (remain >= temp)
remain -= temp;
}
for (int i = temp / 2; i > 0; i = i - 2)
{
for (int j = 0; j < (temp / 2 - i) / 2; j++)
cout << " ";
for (int j = 0; j < i; j++)
cout << c;
cout << endl;
}
for (int i = 3; i <= temp / 2; i = i + 2)
{
for (int j = 0; j < (temp / 2 - i) / 2; j++)
cout << " ";
for (int j = 0; j < i; j++)
cout << c;
cout << endl;
}
cout << remain;
system("pause");
return 0;
}
測試點2應該是 n=1
測試點3應該是n小於7的情況
把小於7的情況單獨列出來,有空要想一個全面的算法~
#include<iostream>
using namespace std;
int main()
{
int n;
char c;
cin >> n >> c;
int remain = n - 1;//*剩餘數
int temp = 3;
if (n < 7)
{
cout << c << endl;
cout << remain;
system("pause");
return 0;
}
for (int i = 1; i < n; i++)
{
if (remain < temp*2)
break;
temp = i * 2 + 1;// temp 爲 3 7 9 ...
if (remain >= temp*2)
remain -= temp*2;
}
for (int i = temp; i > 0; i = i - 2)
{
for (int j = 0; j < (temp - i) / 2; j++)
cout << " ";
for (int j = 0; j < i; j++)
cout << c;
cout << endl;
}
for (int i = 3; i <= temp; i = i + 2)
{
for (int j = 0; j < (temp - i) / 2; j++)
cout << " ";
for (int j = 0; j < i; j++)
cout << c;
cout << endl;
}
cout << remain;
system("pause");
return 0;
}