1. 奇数幻方
对于输入的奇数m, 将 1 到m*m这些自然数填入 m行m列格子中,使每行、每列及对角线的和相等。输出一种填法及这个相等的和。下面的程序中限制m为不超过15的奇数,当输入0时结束程序。如输入3时,程序输出:
8 1 6
3 5 7
4 9 2
Sum=15
const max=15;
var a:array[1..max,1..max] of integer;
m:integer;
procedure GetAnOddNumberOrZero;
begin
repeat
writeln ('Enter an odd number, no more than 15 ',max,'(0 to stop)');
readln(m);
until (m=0) or odd(m) and (m<=max);
end;
procedure ArrangeMagicMatrix(m:integer);
var row,col,num:integer;
begin
row:=1; col:= (m+1) div 2 ;
a[row,col]:=1;
for num:=2 to m*m do
begin
if (num-1) mod m=0 then row:=row+1
else
begin
if row=1 then row:=m
else dec(row) ;
if col=m then col:=1
else inc(col) ;
end;
a[row,col]:=num ;
end;
end;
procedure Print(m:integer);
var row,col:integer;
begin
for row:=1 to m do
begin
for col:=1 to m do write( a[row, col]:5);
writeln;
end;
writeln ('Sum=', (m*m+1)*m div 2 );
end;
begin
repeat
GetAnOddNumberOrZero;
if m<>0 then
begin
ArrangeMagicMatrix(m);
Print(m);
end;
until m=0;
end.
2. 最大和子矩阵
求元素之和最大的子方阵:在m×n (m,n ≤20)的正整数数字方阵中,找出一个p × q 的子 阵(1≤p≤m, 1≤q≤n )使其元素之和最大。例如,下面5 × 4 的数字阵中,元素之和最大的一个2 × 3子阵。
var a:array[1..20,1..20] of integer;
m,n,p,q,i,j,max,p1,q1,s,i1,j1:integer;
begin
for i:=1 to 20 do
for j:=1 to 20 do
a[i,j]:=0;
readln(m,n);
for i:=1 to m do
begin
for j:=1 to n do read(a[i,j]);
readln;
end;
readln(p,q);
max:=0;
for i:=1 to m-p+1 do
for j:=1 to n-q+1 do
begin
s:=0 ;
for i1:=i to p+i-1 do
for j1:=j to q+j-1 do
s:=s+a[i1,j1] ;
if s>max then
begin
max:=s ;
p1:=i;
q1:=j;
end;
end;
for i:=p1 to p1+p-1 do
begin
for j:=q1 to q1+q-1 do
write(a[i,j]:3);
writeln;
end;
end.