Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:
Consider an nn by nn chessboard. Its rows are numbered from 11 to nn from the top to the bottom. Its columns are numbered from 11 to nn from the left to the right. A cell on an intersection of xx-th row and yy-th column is denoted (x,y)(x,y). The main diagonal of the chessboard is cells (x,x)(x,x) for all 1≤x≤n1≤x≤n.
A permutation of {1,2,3,…,n}{1,2,3,…,n} is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly 1+2+…+n1+2+…+n such cells) into nn connected regions satisfying the following constraints:
- Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.
- The xx-th region should contain cell on the main diagonal with number xx for all 1≤x≤n1≤x≤n.
- The number of cells that belong to the xx-th region should be equal to xx for all 1≤x≤n1≤x≤n.
- Each cell under and on the main diagonal should belong to exactly one region.
Input
The first line contains a single integer nn (1≤n≤5001≤n≤500) denoting the size of the chessboard.
The second line contains nn integers p1p1, p2p2, ..., pnpn. pipi is the number written on cell (i,i)(i,i). It is guaranteed that each integer from {1,…,n}{1,…,n} appears exactly once in p1p1, ..., pnpn.
Output
If no solution exists, output −1−1.
Otherwise, output nn lines. The ii-th line should contain ii numbers. The jj-th number on the ii-th line should be xx if cell (i,j)(i,j) belongs to the the region with xx cells.
Examples
input
Copy
3 2 3 1
output
Copy
2 2 3 3 3 1
input
Copy
5 1 2 3 4 5
output
Copy
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
Note
The solutions to the examples are illustrated in the following pictures:
正在上传…重新上传取消
思路:
水题,详细请看代码
代码:
int a[600][600],b[600][600];
int n;
void dfs(int x,int y,int k){//位置,以及数
if(b[k][k]<=1){//基例
return ;
}
if(y-1>=1&&!a[x][y-1]){//左移,别超边界
a[x][y-1]=a[k][k];
b[k][k]--;
dfs(x,y-1,k);
}else if(x+1<=n&&!a[x+1][y]){//左移后下移
a[x+1][y]=a[k][k];
b[k][k]--;
dfs(x+1,y,k);
}else{
a[x+1][y-1]=a[k][k];//左移后下移后再右移
b[k][k]--;
dfs(x+1,y-1,k);
}
}
void solve(){
cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i][i];
b[i][i]=a[i][i];
}
for(int i=1;i<=n;++i){
dfs(i,i,i);
}
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(a[i][j]==0)continue;
cout<<a[i][j]<<' ';
}cout<<'\n';
}
}