partition.c 1.85 KB
/* The partition problem */
/* prob049 @ csplib.org (by Daniel Diaz) */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <paccs.h>

int main(int argc, char *argv[])
{
  fd_int *vs;
  fd_int *sqs0; //, *sqs1;
  int N = 4;
  int values, sum, sq_sum;
  int solutions = 0, one_solution = 1;
  int i;

  fd_init(&argc, &argv);

  for (i = 1; i < argc; ++i)
    if (!strcmp(argv[i], "--all"))
      one_solution = 0;
    else
      N = atoi(argv[i]);

  if ((vs = malloc(2 * N * sizeof(*vs))) == NULL ||
      (sqs0 = malloc(N * sizeof(*sqs0))) == NULL)
    fd__fatal("could not allocate enough memory");

  values = 2 * N;
  sum = N * (2 * N + 1);
  sq_sum = N * (2 * N + 1) * (4 * N + 1) / 3;

  for (i = 0; i < values; ++i)
    vs[i] = fd_new(1, values);

  fd_all_different(vs, values);

  fd_sum(vs, N, sum / 2);
  fd_sum(vs + N, N, sum / 2);

#if 0
  for (i = 0; i < N; ++i)
    {
      sqs0[i] = fd_new(1, values * values);
      fd_var_eq_times(sqs0[i], vs[i], vs[i]);

//      sqs1[i] = fd_new(1, values * values);
//      fd_var_eq_times(sqs1[i], vs[N + i], vs[N + i]);
    }
  fd_sum(sqs0, N, sq_sum / 2);
#else
  fd_sum_prod(vs, vs, N, sq_sum / 2);
//  fd_sum_prod(vs + N, vs + N, N, sq_sum / 2);
#endif

  for (i = 0; i < N - 1; ++i)
    {
      fd_lt(vs[i], vs[i + 1]);
      fd_lt(vs[N + i], vs[N + i + 1]);
    }

  fd_lt(vs[0], vs[N]);

  while (fd_solve() == FD_OK)
    {
      printf("solution %d:\n", ++solutions);

      for (i = 0; i < N; ++i)
	{
	  fd_print(vs[i]);
	  putchar(' ');
	}
      putchar('\n');

      for (i = 0; i < N; ++i)
	{
	  fd_print(vs[N + i]);
	  putchar(' ');
	}
      putchar('\n');

#if !(defined(LOCAL_SEARCH) || defined(DISTRIBUTED_SOLVER))
      if (one_solution)
#endif
	break;
    }

  if (solutions)
    printf("%d solutions found\n", solutions);
  else
    printf("inconsistent CSP\n");

  fd_end();

  return !solutions;
}