# 开始使用MiniZinc

MiniZinc是一个用来描述整数和实数的优化约束和决策问题的语言，它允许用户以接近问题的数学公式的方式编写模型。

MiniZinc界面如下：

MiniZinc IDE

## 着色问题

``````% 用nc种颜色为澳大利亚地图着色
int: nc = 3;

var 1..nc : wa; var 1..nc: nt; var 1..nc: sa; var 1..nc: q;
var 1..nc : nsw; var 1..nc: v; var 1..nc: t;

constraint wa != nt;
constraint wa != sa;
constraint nt != sa;
constraint nt != q;
constraint sa != q;
constraint sa != nsw;
constraint sa != v;
constraint q != nsw;
constraint nsw != v;

solve satisfy;

output ["wa=\(wa) \t nt=\(nt) \t sa=\(sa)\n",
"q=\(q) \t nsw=\(nsw) \t v=\(v)\n",
"t=\(t)\n"];
``````

`int: nc = 3;` 这一行定义并赋值了`nc`这个参数，它是int（整数）类型，值为3.

`var 1..nc : wa;` 这一条语句定义了一个名为`wa`的决策变量，他的范围是1~nc（都包含），类型是整数。

`constraint wa != nt;` 这是一条约束，约束以`constraint`开头，这一条语句的意思是决策变量`wa`不能与`nt`相等。

`solve satisfy;` 这一条语句是表示这是一个满足问题。

``````output ["wa=\(wa) \t nt=\(nt) \t sa=\(sa)\n",
"q=\(q) \t nsw=\(nsw) \t v=\(v)\n",
"t=\(t)\n"];
``````

``````Compiling aust.mzn
Running aust.mzn
wa=3     nt=2    sa=1
q=3      nsw=2   v=3
t=1
----------
Finished in 398msec
``````

## 背包问题

``````enum FRUIT = {BANANA, APPLE, ORGANGE};
int: capacity = 18;
array[FRUIT] of int: value = [8, 19, 29];
array[FRUIT] of int: size = [3, 5, 8];

array[FRUIT] of var int: amt;

constraint forall(i in FRUIT)(amt[i] >= 0);
constraint sum(i in FRUIT)(size[i] * amt[i]) <= capacity;

solve maximize sum(i in FRUIT)(value[i] * amt[i]);

output["Amount=", show(amt)];
``````

`enum FRUIT = {BANANA, APPLE, ORGANGE};` 这条语句定义并赋值了一个枚举型变量。

`constraint forall(i in FRUIT)(amt[i] >= 0);` 语句表示以`FRUIT`中的量为迭代变量，`amt`中迭代变量相应的值都不小于0.

## 建立模型

``````enum PRODUCT;
array[PRODUCT] of float: profit;

enum RESOURCE;
array[RESOURCE] of float: capacity;

array[PRODUCT, RESOURCE] of float: consumption;

array[PRODUCT] of var int: produce;

constraint forall(p in PRODUCT)(produce[p] >= 0);
constraint forall(r in RESOURCE)(
sum(p in PRODUCT)(consumption[p, r] * produce[p]) <= capacity[r]
);

solve maximize sum(p in PRODUCT)(profit[p] * produce[p]);
``````

``````% filename.dzn
PRODUCT = {AP, BP, CP, DP, EP};
profit =  [12.0, 16.0, 13.0, 11.0, 14.0];
RESOURCE = {AR, BR, CR, DR};
capacity = [5567, 3200, 4000, 2800];
consumption = [| 1.3, 1.3, 1.3, 0.5
| 0.1, 1.5, 0.3, 0.1
| 1.5, 0.5, 1.0, 1.0
| 1.6, 1.4, 1.4, 0.1
| 1.8, 0.7, 0.1, 1.6 |];
``````