Ç263 264 283 309
编辑 @Peter Taylor保存了几个字节-比我希望的要少。然后2个字节用于分配更多的内存,现在我可以尝试更大的大小,但是这变得非常耗时。
注意在添加说明时,我发现我在浪费字节,将网格保留在R数组中-这样您就可以看到找到的解决方案...不需要挑战!
我在高尔夫版本中将其删除
一个高尔夫C程序,可以在合理的时间内实际找到n = 1..10的答案。
s,k,n,V[9999],B[9999],i,b;K(l,w,u,t,i){for(t=u&t|u*2&t*4|u/2&t/4,--l; i--;)V[i]&t||(b=B[i]+w,l?b+(n+2)/3*2*l>s&&K(l,b,V[i],u,k):b>s?s=b:0);}main(v){for(scanf("%d",&n);(v=V[i]*2)<1<<n;v%8<6?B[V[k]=v+1,k++]=b+1:0)V[k]=v,b=B[k++]=B[i++];K(n,0,0,0,k);printf("%d",s);}
我的测试:
7-> 26于10秒
8-> 36于18秒
9-> 42于1162秒
少打高尔夫球,试图解释
#include <stdio.h>
int n, // the grid size
s, // the result
k, // the number of valid rows
V[9999], // the list of valid rows (0..to k-1) as bitmasks
B[9999], // the list of 'weight' for each valid rows (number of set bits)
R[99], // the grid as an array of indices pointing to bitmask in V
b,i; // int globals set to 0, to avoid int declaration inside functions
// recursive function to fill the grid
int K(
int l, // number of rows filled so far == index of row to add
int w, // number of crosses so far
int u, // bit mask of the preceding line (V[r[l-1]])
int t, // bit mask of the preceding preceding line (V[r[l-2]])
int i) // the loop variables, init to k at each call, will go down to 0
{
// build a bit mask to check the next line
// with the limit of 3 crosses we need to check the 2 preceding rows
t = u&t | u*2 & t*4 | u/2 & t/4;
for (; i--; )// loop on the k possibile values in V
{
R[l] = i; // store current row in R
b = B[i] + w; // new number of crosses if this row is accepted
if ((V[i] & t) == 0) // check if there are not 3 adjacent crosses
// then check if the score that we can reach from this point
// adding the missing rows can eventually be greater
// than the current max score stored in s
if (b + (n + 2) / 3 * 2 * (n - l - 1) > s)
if (l > n-2) // if at last row
s = b > s ? b : s; // update the max score
else // not the last row
K(l + 1, b, V[i], u, k); // recursive call, try to add another row
}
}
int main(int j)
{
scanf("%d", &n);
// find all valid rows - not having more than 2 adjacent crosses
// put valid rows in array V
// for each valid row found, store the cross number in array B
// the number of valid rows will be in k
for (; i<1 << n; V[k] = i++, k += !b) // i is global and start at 0
for (b = B[k] = 0, j = i; j; j /= 2)
b = ~(j | -8) ? b : 1, B[k] += j & 1;
K(0,0,0,0,k); // call recursive function to find the max score
printf("%d\n", s);
}