partition.c
1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* The partition problem */
/* prob049 @ csplib.org (by Daniel Diaz) */
#include <stdio.h>
#include <stdlib.h>
#include "fdc_int.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;
}