描述
Consider a regular triangular area, divide it into four equal triangles of half height and remove the one in the middle. Apply the same operation recursively to each of the three remaining triangles. If we repeated this procedure infinite times, we'd obtain something with an area of zero. The fractal that evolves this way is called the Sierpinski Triangle. Although its topological dimension is 2, its Hausdorff-Besicovitch dimension is log(3)/log(2)~1.58, a fractional value (that's why it is called a fractal). By the way, the Hausdorff-Besicovitch dimension of the Norwegian coast is approximately 1.52, its topological dimension being 1.
For this problem, you are to outline the Sierpinski Triangle up to a certain recursion depth, using just ASCII characters. Since the drawing resolution is thus fixed, you'll need to grow the picture appropriately. Draw the smallest triangle (that is not divided any further) with two slashes, to backslashes and two underscores like this:
/\ /__\
To see how to draw larger triangles, take a look at the sample output.
输入
The input contains several testcases. Each is specified by an integer n. Input is terminated by n=0. Otherwise 1<=n<=10 indicates the recursion depth.
输出
For each test case draw an outline of the Sierpinski Triangle with a side's total length of 2n characters. Align your output to the left, that is, print the bottom leftmost slash into the first column. The output must not contain any trailing blanks. Print an empty line after each test case.
样例输入
3 2 1 0
样例输出
/\ /__\ /\ /\ /__\/__\ /\ /\ /__\ /__\ /\ /\ /\ /\ /__\/__\/__\/__\ /\ /__\ /\ /\ /__\/__\ /\ /__\
提示
The Sierpinski-Triangle up to recursion depth 7
解题分析
观察样例输入输出得到规律性结果,然后进一步地推导出表达式,以及存储上一个三角形的思想,把每一行都正确地表达,最后递归地调用,直到成功生成了我们想要的那个阶数的三角形后再停止。因为我们发现了一个三角形与三角形之间的一个递推公式吧,然后不断地反复调用即可。
代码实现
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <list>
#include <bitset>
#define MAXN 1050
using namespace std;
string triangle[MAXN];
string tmp[MAXN];
int N;
void f(int n){
if(n==N+1){
int len=pow(2,N);
for(int i=0;i<len;i++){
cout<<triangle[i]<<endl;
}
return;
}
if(n==1){
triangle[0]=tmp[0]=" /\\";
triangle[1]=tmp[1]="/__\\";
}
else{
int len=pow(2,n);
string tmp1;
for(int i=0;i<len/2;i++){
tmp1+=' ';
}
for(int i=0;i<len/2;i++){
triangle[i]=tmp1+tmp[i];
}
for(int i=len/2,m=0,j=pow(2,n-2)*2-1;i<len;i++,j--,m++){
tmp1="";
for(int i=0;i<j;i++){
tmp1+=' ';
}
triangle[i]=tmp[m]+tmp1+tmp[m];
}
for(int i=0;i<len;i++){
tmp[i]=triangle[i];
}
}
f(n+1);
}
int main(){
int n;
while(cin>>n){
if(n==0) break;
N=n;
f(1);
cout<<endl;
}
return 0;
}