Original title link: http: //www.dotcpp.com/oj/problem1097.html
Title Description
Serpentine matrix is a triangular matrix of a natural number 1 sequentially arranged in the beginning.
Entry
The title plurality of sets of data, each data consisting of integer N by one. (N is not larger than 100)
Export
For each set of data and outputs a matrix of N rows of serpentine. Do extra blank line between the two sets of output. Digital Matrix triangle in the same line separated by a space. End of the line do extra spaces.
Sample input
5
Sample Output
1 3 6 10 15
2 5 9 14
4 8 13
7 12
11
Problem-solving ideas
0 - 15. 1. 3. 6 10
12 is 14. 9. 5
2 - 13 is. 4. 8
. 3 - 12 is. 7
. 4 -. 11
us analyze, problems like this are to be linked to the rows and columns,
for the first row 0 The number is 1 1 + 2 (0 + 2) 1 + 2 + 3 1 + 2 + 3 + 4 1 + 2 + 3 + 4 + 5
for the first number is the first line 2 2 + 3 (1 + 2 ) 2 + 3 + 4 2 + 3 + 4 + 5
for the second row is the first number 4 4 + 4 (2 + 2) 4 + 4 + 5
for the third row first number is 7 . 7 + 5 ( 3 + 2)
to the first number is the fourth row 11
by observing the second number per row = first row i + 2 + number is followed by the accumulation of long plus q determines the starting only thereafter q is incremented by summing need to be the i-th row and q = +2
had then determine where the start number in the line
0 -. 1
. 1 - 2
2 -. 4
. 3 -. 7
. 4 -11
Where it is easy to see (the start line number 0 is the set of 1) (starting point of the previous line) 2 = 1 (starting value of the previous line) + 1 (current number of lines) = 4 2 + 2 ( the current line number) 7 = 4 (on line starting value) + 3 (the current line number) 11 = 7 (on line starting value) +4 (the current number of rows)
so what we are dealing with an array of
written expression: current initial value equal to the current line number of a line +
expression: a [i] = a [ i-1] + i
Another point is that
from the beginning of the first row, the number of elements on each row line less than a
Reference Code
#include<iostream>
#include<cstdio>
#define Max 101
using namespace std;
int main()
{
int n,a[Max];
int p=1,q;
int k;
//循环录入每行的初始值
for(int i = 0;i < 101;++i)
{
if(i != 0)
{
a[i] = a[i-1]+i;
}
else
{
a[i] = 1;
}
}
while(cin>>n)
{
//k是列数
k = n;
for(int i=0;i <n;++i)
{
p = a[i];
q = i+2;
for(int j=0;j < k;++j)
{
if(j == 0)
{
cout << p <<" ";
}else
{
p=p+q;
q +=1;
//到达尾部就不要输出空格
if(j ==k-1)
{
cout << p ;
}else
{
cout << p <<" ";
}
}
}
--k; //列数相对上一行少1
cout<<endl;
}
}
return 0;
}