सी 263 264 283 309
संपादित करें कुछ बाइट्स ने thx @Peter टेलर को बचाया - जितना मुझे आशा थी उससे कम। तब 2 बाइट्स कुछ और मेमोरी आवंटित करते थे, अब मैं बड़े आकार की कोशिश कर सकता हूं, लेकिन इसमें बहुत समय लगता है।
नोट स्पष्टीकरण जोड़ते समय, मुझे पता चला कि मैं आर सरणी में ग्रिड रखने के लिए बाइट्स बर्बाद कर रहा हूं - ताकि आप पाए गए समाधान को देख सकें ... यह इस चुनौती के लिए अनुरोध नहीं किया गया है !!
मैंने इसे गोल्फ संस्करण में हटा दिया
एक गोल्फ सी कार्यक्रम जो वास्तव में उचित समय में 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 -> 10 में 26 सेकंड
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);
}