B - Practical Computing Editorial by en_translator
Solution
Let us finding the values of \(a_{i,j}\) according to the Problem Statement. We must set the length of each sequence (or each array in the program) appropriately according to:
- For each \(i\) \((0\leq i \leq N-1)\), the length of \(A_i\) is \(i+1\).
One straightforward way to achieve it is:
vector<vector<int>> a(N);
for(int i=0;i<N;i++){
a[i] = vector<int>(i+1);
}
Alternatively, this time you may create an array of size \(N \times N\) and use only some of the slots.
vector a(N,vector<int>(N));
Next, let us find the values of \(a_{i,j}\) according to the following description:
For each \(i\) and \(j\) \((0\leq i \leq N-1, 0 \leq j \leq i)\), the \((j+1)\)-th term of \(A_i\), denoted by \(a_{i,j}\), is defined as follows.
- \(a_{i,j}=1\), if \(j=0\) or \(j=i\).
- \(a>_{i,j} = a_{i-1,j-1} + a_{i-1,j}\), otherwise.
We can implement “\(a_{i,j}=1\), if \(j=0\) or \(j=i\)” by checking if it holds that “\(j=0\) or \(j=i\),” and let \(a_{i,j}=1\), when determining the value of \(a_{i,j}\).
It also says that “\(a>_{i,j} = a_{i-1,j-1} + a_{i-1,j}\), otherwise,” implying that you need to find \(a_{i-1,j-1}\) and \(a_{i-1,j}\) before finding \(a_{i,j}\). To do so, write a loop that finds \(a_{i,j}\) for \(i=0,1,\ldots\) in this order. (Note that, when \(i=0\), we don’t have \(a_{i-1,j-1}\), but it is OK since only valid \(j\) when \(i=0\) is \(j=0\), which satisfies “\(j=0\) or \(j=i\).”)
Sample code
#include <bits/stdc++.h>
using namespace std;
int main(){
int N;
cin>>N;
vector a(N,vector<int>(N));
for(int i=0;i<N;i++){
a[i] = vector<int>(i+1);
}
for(int i=0;i<N;i++){
for(int j=0;j<i+1;j++){
if(j==0||j==i)a[i][j] = 1;
else{
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
}
}
for(int i=0;i<N;i++){
for(int j=0;j<i+1;j++){
if(j!=0)cout<<' ';
cout<<a[i][j];
}
cout<<endl;
}
return 0;
}
Bonus
The sequences you are asked to find is what is called Pascal’s triangle. It is known that the value \(a_{n,r}\) is equal to \({}_nC_r\), the number of ways to choose \(r\) out of \(n\) items.
posted:
last update: