主题:[讨论]2004年第四题速度太慢了!!!
2004年第四题
2004-4
对于正整数N(3<=N<=20),可以画出N阶的回形方阵.如N=7,则方阵为:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
对于N阶回形矩阵,从左上角出发,每步可向右或向下走一格,走N*2-2步,可以到达右下角.
我们把这样的路径上所有格子中的数值之和,叫做该路径的长度.
本题要求,对于给出的N值,求出N阶回形矩阵有多少路径的长度为素数?
如N=3时,路径长度有
1 1 1 1 1 1 1 1 1
1 2 1 1 2 1 1 2 1
1 1 1 1 1 1 1 1 1
长度=5 长度=6 长度=6
1 1 1 1 1 1 1 1 1
1 2 1 1 2 1 1 2 1
1 1 1 1 1 1 1 1 1
长度=6 长度=6 长度=5
因此说,3阶回形矩阵有2条路径的长度为素数
我的方法是:
CLS
INPUT N
DIM A(N, N), S(100), X(100), Y(100), B(10000)
FOR I = 1 TO (N + 1) \ 2
FOR J = 1 TO (N + 1) \ 2
IF I > J THEN A(I, J) = J ELSE A(I, J) = I
A(I, N + 1 - J) = A(I, J)
A(N + 1 - I, J) = A(I, J)
A(N + 1 - I, N + 1 - J) = A(I, J)
NEXT J
NEXT I
FOR I = 2 TO N * N
F = 0
FOR J = 2 TO INT(SQR(I))
IF I MOD J = 0 THEN F = 1: EXIT FOR
NEXT J
IF F = O THEN B(I) = I
NEXT I
FOR I = 1 TO 2
READ v(I, 1), v(I, 2)
NEXT I
DATA 0,1,1,0
P = 1: X = 1: Y = 1: X(P) = X: Y(P) = Y: I = 0
WHILE P > 0
I = I + 1
IF I <= 2 THEN
X = X(P) + v(I, 1): Y = Y(P) + v(I, 2)
IF X >= 1 AND X <= N AND Y >= 1 AND Y <= N THEN
P = P + 1
S(P) = I
X(P) = X
Y(P) = Y
I = 0
IF X = N AND Y = N THEN GOSUB 10
END IF
ELSE I = S(P)
P = P - 1
X = X - X(P)
Y = Y - Y(P)
END IF
WEND
PRINT T#
END
10 S = 0
FOR M = 1 TO P
S = S + A(X(M), Y(M))
NEXT M
IF B(S) <> 0 THEN T# = T# + 1
RETURN
当N大于10的时候速度非常慢!
大虾们帮我改进一下!!!!!!
2004-4
对于正整数N(3<=N<=20),可以画出N阶的回形方阵.如N=7,则方阵为:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
对于N阶回形矩阵,从左上角出发,每步可向右或向下走一格,走N*2-2步,可以到达右下角.
我们把这样的路径上所有格子中的数值之和,叫做该路径的长度.
本题要求,对于给出的N值,求出N阶回形矩阵有多少路径的长度为素数?
如N=3时,路径长度有
1 1 1 1 1 1 1 1 1
1 2 1 1 2 1 1 2 1
1 1 1 1 1 1 1 1 1
长度=5 长度=6 长度=6
1 1 1 1 1 1 1 1 1
1 2 1 1 2 1 1 2 1
1 1 1 1 1 1 1 1 1
长度=6 长度=6 长度=5
因此说,3阶回形矩阵有2条路径的长度为素数
我的方法是:
CLS
INPUT N
DIM A(N, N), S(100), X(100), Y(100), B(10000)
FOR I = 1 TO (N + 1) \ 2
FOR J = 1 TO (N + 1) \ 2
IF I > J THEN A(I, J) = J ELSE A(I, J) = I
A(I, N + 1 - J) = A(I, J)
A(N + 1 - I, J) = A(I, J)
A(N + 1 - I, N + 1 - J) = A(I, J)
NEXT J
NEXT I
FOR I = 2 TO N * N
F = 0
FOR J = 2 TO INT(SQR(I))
IF I MOD J = 0 THEN F = 1: EXIT FOR
NEXT J
IF F = O THEN B(I) = I
NEXT I
FOR I = 1 TO 2
READ v(I, 1), v(I, 2)
NEXT I
DATA 0,1,1,0
P = 1: X = 1: Y = 1: X(P) = X: Y(P) = Y: I = 0
WHILE P > 0
I = I + 1
IF I <= 2 THEN
X = X(P) + v(I, 1): Y = Y(P) + v(I, 2)
IF X >= 1 AND X <= N AND Y >= 1 AND Y <= N THEN
P = P + 1
S(P) = I
X(P) = X
Y(P) = Y
I = 0
IF X = N AND Y = N THEN GOSUB 10
END IF
ELSE I = S(P)
P = P - 1
X = X - X(P)
Y = Y - Y(P)
END IF
WEND
PRINT T#
END
10 S = 0
FOR M = 1 TO P
S = S + A(X(M), Y(M))
NEXT M
IF B(S) <> 0 THEN T# = T# + 1
RETURN
当N大于10的时候速度非常慢!
大虾们帮我改进一下!!!!!!