Hãy luôn nhớ cảm ơn và vote 5*
nếu câu trả lời hữu ích nhé!
Dùng file cho tiện nhập nhé.
uses crt;
var f,g:text; t,n,m,i,j,x,y,x1,y1:longint; a:array[1..10000000]of longint;
kq:array[1..1000,1..1000] of longint;
kt:array[1..1000,1..1000] of boolean;
begin
assign(f,'input.pas');reset(f);
readln(f,n,m);
for i:=1 to n do
begin
for j:=1 to m do read(f,a[(i-1)*m+j]);
readln(f);
end;
close(f);
assign(f,'output.pas');rewrite(f);
for i:=1 to n*m do
for j:=i+1 to n*m do
if a[i]>a[j] then
begin
t:=a[i];
a[i]:=a[j];
a[j]:=t;
end;
x:=1; y:=0; x1:=0; y1:=1;
for i:=1 to n*m do
begin
if (y+y1>m)or((kt[x,y+y1])and(y1=1)) then
begin
x1:=1;
y1:=0;
end else
if (x+x1>n)or((kt[x+x1,y])and(x1=1)) then
begin
x1:=0;
y1:=-1;
end else
if (y+y1=0)or((kt[x,y+y1])and(y1=-1)) then
begin
x1:=-1;
y1:=0;
end else
if (x+x1=0)or((kt[x+x1,y])and(x1=-1)) then
begin
x1:=0;
y1:=1;
end;
//writeln(x1,' ',y1,' ',x,' ',y);
x:=x+x1;
y:=y+y1;
kq[x,y]:=a[i];
kt[x,y]:=true;
end;
for i:=1 to n do
begin
for j:=1 to m do write(f,kq[i,j],' ');
writeln(f);
end;
close(f);
end.
Hãy giúp mọi người biết câu trả lời này thế nào?
Code
#include <bits/stdc++.h>
using namespace std;
int n,m;
int partition(int arr[], int low, int high){
int i = low;
int j = high;
int pivot = arr[low];
while (i < j)
{
while (pivot >= arr[i])
i++;
while (pivot < arr[j])
j--;
if (i < j)
swap(arr[i], arr[j]);
}
swap(arr[low], arr[j]);
return j;
}
void quickSort(int arr[], int low, int high){
if (low < high)
{
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
void SpiralMatrix(int arr[]){
int mat[n][m];
int top = 0, bottom = n - 1, left = 0, right = m - 1;
int index = 0;
while (1) {
if (left > right) break;
for (int i = left; i <= right; i++) mat[top][i] = arr[index++];
top++;
if (top > bottom) break;
for (int i = top; i <= bottom; i++) mat[i][right] = arr[index++];
right--;
if (left > right) break;
for (int i = right; i >= left; i--) mat[bottom][i] = arr[index++];
bottom--;
if (top > bottom) break;
for (int i = bottom; i >= top; i--) mat[i][left] = arr[index++];
left++;
}
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
int main(){
cin >> n >> m;
int arr[n*m];
for (int i = 0; i < n*m; i++) cin >> arr[i];
quickSort(arr, 0, n*m - 1);
int mat[n][m];
cout << endl;
SpiralMatrix(arr);
return 0;
}
Ý tưởng
+ Nhập mảng 2 chiều rồi chuyển về mảng 1 chiều
+ Dùng thuật toán Quick Sort để sắp xếp mảng theo chiều tăng dần
+ Duyệt qua mảng và chọn từng phần tử để điền vào ma trận theo thứ tự xoắn ốc. Thứ tự này được duy trì bằng 4 vòng lặp - trái, phải, dưới và trên. Mỗi vòng lặp in hàng / cột tương ứng của nó trong ma trận xoắn ốc
Hãy giúp mọi người biết câu trả lời này thế nào?
Bảng tin
0
16
0
Mình hâm mộ bạn lắm lun:3
2376
46183
1806
haha tks bạn :D