主题:耐人寻味的字符串题
网络爱好者
[专家分:60] 发布于 2006-08-22 16:38:00
有2N个盒子,盒子上从1到N自然数进行标号,每个数字会出现在两个盒子上。下面将盒子排成一排,要求是:标号1的两个盒子之间隔1个盒子;标号2的两个盒子之间隔2隔盒子……标号N的两个盒子之间隔N个盒子。如N=3,可能的排列是2 3 1 2 1 3。编程实现,对给定的N(3≤N≤40),求出一种可行排列。如没有可行排列,输出“No answer”。
回复列表 (共9个回复)
沙发
moz [专家分:37620] 发布于 2006-08-22 19:58:00
这道题做过,忘了.老了.
板凳
moz [专家分:37620] 发布于 2006-08-22 20:03:00
defint a-z
n = 11
n2 = n * 2
dim a(n2), b(n2), c(n)
for i = 1 to n2
if a(i) = 0 then
for k = k + 1 to n
if c(k) = 0 then
j = i + k + 1
if j <= n2 then
if a(j) = 0 then
c(k) = 1
a(i) = k
a(j) = k
p = p + 1
b(p) = i
k = 0
exit for
end if
end if
end if
next
if p = n then
for k = 1 to n2
print a(k);
next
print
answer& = answer& + 1
end if
if k > n then
i = b(p)
k = a(i)
c(k) = 0
a(i) = 0
a(i + k + 1) = 0
p = p - 1
i = i - 1
end if
end if
if p < 0 then exit for
next
if answer = 0 then print "no answer" else print anmwer
3 楼
moz [专家分:37620] 发布于 2006-08-22 20:07:00
按道理程序写到这样算可以的了,够短小精悍的了.
但题目居然要算到40去,老半天看不到影子.
还得改进?[em10]
4 楼
moz [专家分:37620] 发布于 2006-08-23 01:14:00
只求一种可行排列,可还是太慢.
defint a-z
n=40
n2=n*2
dim a(n2),b(n),c(n)
timer1#=timer
for i=1 to n2
if a(i)=0 then
for k=k+1 to n
if c(k)=0 then
j=i+k+1
if j<=n2 then
if a(j)=0 then
c(k)=k
a(i)=k
a(j)=k
p=p+1
b(p)=i
k=0
exit for
end if
end if
end if
next
if p=n then exit for
if k>n then
i=b(p)
k=a(i)
c(k)=0
a(i)=0
a(i+k+1)=0
p=p-1
i=i-1
end if
end if
if p<0 then exit for
next
if p<0 then
print"no answer"
else
for k=1 to n2:print a(k);:next:print
end if
print timer-timer1#
5 楼
moz [专家分:37620] 发布于 2006-08-23 01:49:00
想起了richone的先走出口少的路,所以把路倒过来走,
又改了一次,40也很快了,39也很快了.
可问题还是存在,一些无解的38,37,34,33,31,29,甚至是13,还是半天算不完,没办法.
defint a-z
n=28
n2=n*2
dim a(n2),b(n),c(n)
cls
timer1#=timer
k=n+1
for i=1 to n2
if a(i)=0 then
for k=k-1 to 1 step-1
if c(k)=0 then
j=i+k+1
if j<=n2 then
if a(j)=0 then
c(k)=k
a(i)=k
a(j)=k
p=p+1
b(p)=i
k=n+1
exit for
end if
end if
end if
next
if p=n then exit for
if k=0 then
i=b(p)
k=a(i)
c(k)=0
a(i)=0
a(i+k+1)=0
p=p-1
if p<0 then exit for
i=i-1
end if
end if
next
if p<0 then
print"no answer"
else
for k=1 to n2:print a(k);:next:print
end if
print timer-timer1#
6 楼
shiyr [专家分:390] 发布于 2006-08-23 13:10:00
一道数学题 可以通过构造法求出可行解 ... 如果知道这种方法后就会觉得N<=40实在是太小了 ...
搜索也是可以轻易解决N=40的吧 ... 我以前写的可以做到140 ...
ps . 好久没来这逛逛了
7 楼
moz [专家分:37620] 发布于 2006-08-23 22:12:00
喔,愿领教.
我记得你,你的操作系统写得怎样了?
8 楼
shiyr [专家分:390] 发布于 2006-08-24 11:12:00
呵呵moz你好 .
其实数学方法我现在也不怎么记得了 ... 是一个在数学竞赛组的同学告诉我的 =.=
下次问到了再发 ...
os早就没弄了 ... 毕竟太没影了 ... 我现在只要弄个国家队就满足了
9 楼
世界型帅哥 [专家分:0] 发布于 2006-10-26 20:28:00
moz大哥,我倒![em10]
我来回复