Skip to content

Instantly share code, notes, and snippets.

@joriki
Created April 15, 2016 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joriki/dd3e22970f0e8d13a77c02e681f3982e to your computer and use it in GitHub Desktop.
Save joriki/dd3e22970f0e8d13a77c02e681f3982e to your computer and use it in GitHub Desktop.
Find the maximum total value of n nodes after certain moves; see http://math.stackexchange.com/questions/1743298.
import java.util.Arrays;
import java.util.Stack;
public class Question1743298 {
static int used;
static int [] values;
static int n;
static int max;
public static void main (String [] args) {
for (n = 1;;n++) {
System.out.println ();
System.out.println (n + ":");
values = new int [n];
Arrays.fill (values,1);
for (int i = 0;i < n;i++)
values [i] = 1;
max = 0;
recurse (n * (n - 1),n);
}
}
static Stack<Integer> moves = new Stack<Integer> ();
static void recurse (int depth,int total) {
if (depth-- == 0) {
if (total > max) {
System.out.println (" " + total);
int [] tmp = new int [n];
Arrays.fill (tmp,1);
for (int k = 0;k < moves.size ();k += 2) {
Integer i = moves.get (k);
Integer j = moves.get (k + 1);
tmp [j] += tmp [i];
System.out.println (" " + (i + 1) + " -> " + (j + 1) + " " + Arrays.toString (tmp) + ",");
}
max = total;
}
return;
}
for (int i = 0,mask = 1;i < n;i++)
for (int j = 0;j < n;j++,mask <<= 1)
if (i != j && (used & mask) == 0) {
used |= mask;
int value = values [i];
values [j] += value;
moves.push (i);
moves.push (j);
recurse (depth,total + value);
moves.pop ();
moves.pop ();
values [j] -= value;
used &= ~mask;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment