Luogu P5732 [Shenji 5.Xiu 7] Solution to Yang Hui's Triangle Problem

topic

[Deep Basics 5. Xi 7] Yang Hui Triangle

Question description

Given n ( n ≤ 20 ) n(n\le20)n(n20 ) , output the firstnnn lines.

If you don’t know what Yang Hui’s triangle is, you can look for patterns by looking at examples.

Input format

none

Output format

none

Example #1

Sample input #1

6

Sample output #1

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

portal

https://www.luogu.com.cn/problem/P5732

code

/*
C++程序,计算杨辉三角的前n行
*/

#include<iostream>
using namespace std;

long long arr[1005][2015], n, m, i, j, p;

int main()
{
    
    

	cin >> n;
	m = 2 * n - 1;
	
	// 初始化第一行和第二行的数值
	for (i = 0; i < n; i++)
	{
    
    
	    arr[i][n - i - 1] = 1;
	    arr[i][n + i - 1] = 1;
	}
	
	// 计算杨辉三角的每一行
	for (i = 2; i < n; i++)  
	{
    
    
	    for (j = n - i + 1; j < n - 2 + i; j = j + 2)
	        arr[i][j] = (arr[i - 1][j - 1] + arr[i - 1][j + 1]);
	}
	
	// 输出杨辉三角前n行的数值
	for (i = 0; i < n; i++) 
	{
    
    
	    p = 1;
	    for (j = n - i - 1; p < i + 2; j = j + 2)
	    {
    
    
	        cout << arr[i][j] << " "; 
	        p = p + 1;
	    }
	    cout << endl;
	}
	
	return 0;
}

explain

This code is a program for generating Yang Hui triangles. Yang Hui's triangle is a sequence of numbers arranged in a triangle, where each number is equal to the sum of the two numbers above it. The function of the code is to input a positive integer n and then generate an n-line Yang Hui triangle.

The specific implementation process is as follows:

  1. First, a positive integer n is read from standard input.
  2. Calculate the number of columns m of Yang Hui's triangle, its value is 2*n-1.
  3. For each row i, set the elements in column ni-1 and column n+i-1 to 1. This is the boundary condition of Yang Hui's triangle.
  4. Starting from row 2, for each row i, from column n-i+1 to column n-2+i, calculate the elements in the Yang Hui triangle column by column. The calculation method is that the element at this position is equal to the sum of the two elements above it.
  5. Output the results of Yang Hui's triangle. For each row i, output elements column by column from column ni-1 to column n-i+1. It should be noted that the number of output elements in each row is i+1.
  6. The program ends.

Personal test

Personal test AC
Insert image description here

おすすめ

転載: blog.csdn.net/Python_enjoy/article/details/133488725