Skip to content

Instantly share code, notes, and snippets.

@pogin503
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pogin503/7cd8730e1ce01929a9ed to your computer and use it in GitHub Desktop.
Save pogin503/7cd8730e1ce01929a9ed to your computer and use it in GitHub Desktop.
#include "stdio.h"
#include <cmath>
#include <iostream>
#include <vector>
#include <sstream>
#include <iomanip>
typedef std::vector<int> VI;
typedef std::vector<VI> VVI;
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
using namespace std;
VVI solve(int n){
VVI v;
v.resize(n);
if (n < 0){
exit(EXIT_FAILURE);
}
if (n == 1){
v[0].push_back(1);
}else if (n == 2){
v[0].push_back(1);
v[1].push_back(1);
v[1].push_back(1);
}else {
v[0].push_back(1);
v[1].push_back(1);
v[1].push_back(1);
for(int i = 2; i < n; i++){
v[i].resize(i + 1);
}
for(int i = 1; i < n;i++){
for(int j = 0; j < i + 1; j++){
if(j == 0)
v[i][j] = 1;
else if(j == i)
v[i][j] = 1;
else
v[i][j] = v[i - 1][j - 1] + v[i - 1][j];
}
}
}
return v;
}
int calcDigit(int n){
return (int)log10(n) + 1;
}
void pretty_print(int n, VVI &v, int digit_max){
string space = string(digit_max, ' ');
cout.width(digit_max);
cout.fill(' ');
for(unsigned int i = 0; i < v.size(); i++){
for(int space_i = n - i - 1; space_i > 0; space_i--){
cout << space;
}
for(unsigned int j = 0; j < v[i].size(); j++){
cout << setw(digit_max) << v[i][j] << space;
}
for(int space_i = n - i - 1; space_i > 0; space_i--){
cout << space;
}
cout << endl;
}
}
int main(){
int n;
scanf("%d", &n);
VVI v;
v.resize(n);
v = solve(n);
int isize = v.size() - 1;
int jsize = v[isize].size() / 2;
int max_num = v[isize][jsize];
int digit_width = calcDigit(max_num);
pretty_print(n, v, digit_width);
return 0;
}
/*
実行結果
> g++ pascalTriangle.cpp
> ./a.out
10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment